package com.hgkj.cloud.customer.controller;

import com.alibaba.fastjson.JSON;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.hgkj.cloud.base.common.AdminCommon;
import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.base.domain.*;
import com.hgkj.cloud.base.scheme.*;
import com.hgkj.cloud.base.service.*;
import com.hgkj.cloud.customer.common.AjaxJson;
import com.hgkj.cloud.customer.common.ResponseData;
import com.hgkj.cloud.customer.common.ZipUtils;
import com.hgkj.cloud.customer.enums.TasksMethodEnum;
import com.hgkj.cloud.customer.excel.TaskUserExcelParseTool;
import com.hgkj.cloud.customer.file.FileSourceGenerator;
import com.hgkj.cloud.customer.util.DateTimeUtil;
import com.hgkj.cloud.customer.util.ExcleTableCreateUtil;
import com.hgkj.cloud.customer.util.WaterMarkUtil;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 答题入口
 */
@RestController
@Slf4j
@RequestMapping("/testTask")
public class TestTaskController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TenantFrameworksService tenantFrameworksService;
	@Autowired
	private TenantTableTasksService tenantTableTasksService;
	@Autowired
	private SysTenantAuthService sysTenantAuthService;
	@Autowired
	private TenantTableReportsService tenantTableReportsService;
	@Autowired
	private TenantTableReportsAttachedService tenantTableReportsAttachedService;
	@Autowired
	private TenantTableFactorsService mTenantTableFactorsService;
	@Autowired
	private TenantLogsService tenantLogsService;
	@Autowired
	private SysTaskImagesService sysTaskImagesService;
	@Autowired
	private TenantTableTaskInfoService tenantTableTaskInfoService;
	@Autowired
	private SysTableBriefService sysTableBriefService;
	@Autowired
	private EUserService eUserService;
	@Autowired
	private SysTableContentService mSysTableContentService;
	@Autowired
	private SysTableDiagnosisService mSysTableDiagnosisService;
	@Autowired
	private TenantSchemesService mTenantSchemesService;
	@Autowired
	private SysFaqPairService mSysFaqPairService;
	@Autowired
	private SysFaqService mSysFaqService;
	@Autowired
	private ExtTableSclService mExtTableSclService;
	@Autowired
	private FileSourceGenerator fsg;

	@Value("${server.host}")
	private String serverHost;
	@Value("${upload.file.path}")
	private String docpath;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private SqlSession sqlSession;

	@Autowired
	private RemoteService remoteService;
	private static ExecutorService executor;

	@Value("${upload.file.path}")
	private String uploadFilePath;
	@Value("${upload.file.server}")
	private String uploadFileServer;
	@Value("${fileProcess.fileBaseUrl}")
	private String prefixUrl;

	/**
	 * 获取当前可见任务列表
	 *
	 * @param page
	 * @param page_size
	 * @param create_by
	 * @param task_status
	 * @param task_name
	 * @param begin_time
	 * @param end_time
	 * @param framework_id
	 * @param admin_uuid
	 * @return
	 */
	@RequestMapping("/getListTenantTableTasks")
	@ResponseBody
	public ResponseData getListTenantTableTasks(Integer page, Integer page_size, String create_by, Integer task_status,
			String task_name, String begin_time, String end_time, Long framework_id, String admin_uuid,
			String tableUuid) {

		ResponseData mResponseData = new ResponseData();
		if (StringUtils.isEmpty(admin_uuid)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("登录者信息为空");
			return mResponseData;
		}

		Map<String, Object> map = new HashMap<>();
		AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
//        getframeworkDatas(framework_id, adminUserInfoByUuid, map);
		getTreePathDatas(framework_id, adminUserInfoByUuid, map);
		if (create_by != null && !"".equals(create_by)) {
			map.put("create_by", create_by);
		}
		if (task_status != null) {
			map.put("status", task_status);
		}
		if (!StringUtils.isEmpty(tableUuid)) {
			map.put("tableUuid", tableUuid);
		}
		if (task_name != null && !"".equals(task_name)) {
			map.put("name", task_name);
		}
		if (begin_time != null && !"".equals(begin_time)) {
			map.put("beginTime", DateTimeUtil.getUtcFromString(begin_time));
		}
		if (end_time != null && !"".equals(end_time)) {
			map.put("endTime", DateTimeUtil.getUtcFromString(end_time));
		}
		PageInfo pi = new PageInfo();
		if (page != null && page_size != null) {
			pi.setPageSize(page_size);
			pi.setCurrentPage(page);
		}
		Integer count = tenantTableTasksService.findAllTableTaskCount(map);
		List<TenantTableTasks> list = tenantTableTasksService.listAllTableTasks(pi, map);
		Integer listSize = 0;
		Map<String, Object> Newmap = new HashMap<>();
		for (TenantTableTasks task : list) {
			// 修改 tenant_table_tasks 中的user_num Finish_num finish_rate
			/*
			 * Newmap.put("task_uuid", task.getUuid()); Long userCount =
			 * eUserService.listTableTaskUsersCount(Newmap); int finishedCount =
			 * tenantTableTaskInfoService.getUserTaskInfoFinishedCount(Newmap); if
			 * (task.getUser_num() != null) { if (userCount.intValue() !=
			 * task.getUser_num()) { task.setUser_num(userCount.intValue());
			 * logger.info("---修改User_num-- 成功 User_num: " + userCount.intValue());
			 * tenantTableTasksService.updateByPrimaryKey(task); } if (task.getFinish_num()
			 * != null) { if (finishedCount != task.getFinish_num()) {
			 * task.setFinish_num(finishedCount);
			 * logger.info("---修改Finish_num-- 成功 Finish_num: " + finishedCount); if
			 * (task.getUser_num() != 0) { //测评任务下没有用户时进行判断 0不能为被除数 BigDecimal finishRate =
			 * new BigDecimal(finishedCount * 100 / task.getUser_num()); //finishRate
			 * 计算任务完成度 finishRate = finishRate.setScale(2, RoundingMode.HALF_UP); //保留小数点两位
			 * RoundingMode.HALF_UP（四舍五入） task.setFinish_rate(finishRate.doubleValue());
			 * logger.info("---修改Finish_rate-- 成功 Finish_rate: " +
			 * finishRate.doubleValue()); } else { task.setFinish_rate(0.0); }
			 * tenantTableTasksService.updateByPrimaryKey(task); } } list.set(listSize,
			 * task); }
			 */
			if (task.getUser_num() != null && task.getUser_num() != 0) {
				BigDecimal finishRate = new BigDecimal(
						task.getFinish_num() == null ? 0 : task.getFinish_num() * 100 / task.getUser_num()); // finishRate
																												// 计算任务完成度
				finishRate = finishRate.setScale(2, RoundingMode.HALF_UP); // 保留小数点两位 RoundingMode.HALF_UP（四舍五入）
				task.setFinish_rate(finishRate.doubleValue());
			}

			AdminUser adminUserInfoByUuid1 = getAdminUserInfoByUuid(task.getCreate_by());
			if (adminUserInfoByUuid1 == null) { // 专业账号删除后或者测试账号失效后无法搜索出来
				task.setCreate_name("无效账号");
			} else {
				task.setCreate_name(adminUserInfoByUuid1.getReal_name());
			}
			listSize++;
		}
		map.clear();
		map.put("list", list);
		map.put("count", count);
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 查看有报告的测评列表
	 *
	 * @return
	 */
	@RequestMapping("/tableReportList")
	@ResponseBody
	public ResponseData tableReportList(Integer page, Integer page_size, String user_uuid, String user_name,
			String real_name, String table_uuid, String user_gender, Long framework_id, String test_begin_date,
			String test_end_date, String report_level, String admin_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> p_map = new HashMap<String, Object>();
		AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
		List<String> report_levels = new ArrayList<>();
		if (!StringUtils.isEmpty(user_uuid))
			p_map.put("user_uuid", user_uuid);
		if (!StringUtils.isEmpty(user_name))
			p_map.put("user_name", user_name);
		p_map.put("searchName", user_name);
		if (!StringUtils.isEmpty(real_name))
			p_map.put("real_name", real_name);
		if (!StringUtils.isEmpty(table_uuid))
			p_map.put("table_uuid", table_uuid);
		if (!StringUtils.isEmpty(user_gender))
			p_map.put("user_gender", user_gender);
		getReportLevel(report_level, p_map, report_levels);
		// 组织机构
//        getframeworkDatas(framework_id, adminUserInfoByUuid, p_map);
		getTreePathDatas(framework_id, adminUserInfoByUuid, p_map);

		if (!StringUtils.isEmpty(test_begin_date)) {
			p_map.put("test_begin_date", DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
			System.out.println("test_begin_date=" + DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
		}
		if (!StringUtils.isEmpty(test_end_date)) {
			p_map.put("test_end_date", DateTimeUtil.getEndUtcFromString(test_end_date) * 1000);
			System.out.println("test_end_date=" + DateTimeUtil.getUtcFromString(test_end_date) * 1000);
		}
		PageInfo pi = null;
		if (page != null && page_size != null) {
			pi = new PageInfo();
			pi.setCurrentPage(page);
			pi.setPageSize(page_size);
		}
		long listcount = tenantTableReportsService.listTableReportsByMapCount(p_map);
		List<TenantTableReports> lists = tenantTableReportsService.listTableReportsPcByMap(pi, p_map);
		p_map.clear();
		p_map.put("list", lists);
		p_map.put("count", listcount);
		mResponseData.setData(p_map);
		return mResponseData;
	}

	/**
	 * 导出测评任务未完成人员
	 * http://192.168.0.197:8094/cloud-customer/testTask/exUndoneUser?task_uuid=078d63d5-fa7c-11eb-93ec-00163e1269b6
	 *
	 * @param task_uuid
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/exUndoneUser")
	public String excelDcCommom(String task_uuid, HttpServletResponse response, String admin_uuid) throws IOException {
		String fileName = "测评任务未完成人员";
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		// 根据传进来的file对象创建可写入的Excel工作薄
		OutputStream os = response.getOutputStream();
		try {
			WritableWorkbook wwb = null;
			// 创建可写入的Excel工作簿
			wwb = Workbook.createWorkbook(os);
			WritableSheet ws = wwb.createSheet("测评任务未完成人员信息表", 0);
			// 查询数据库中所有的数据
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("task_uuid", task_uuid);
			map.put("finished", 0);
			List<EUser> examineUsers = eUserService.listTableTaskUsers(null, map);

			// 要插入到的Excel表格的行号，默认从0开始
			Label user_name = new Label(0, 0, "用户名");
			Label real_name = new Label(1, 0, "真实姓名");
			Label frame_work = new Label(2, 0, "组织机构");
			ws.addCell(user_name);
			ws.addCell(real_name);
			ws.addCell(frame_work);
			// 组织机构
			for (int i = 0; i < examineUsers.size(); i++) {
				Label user_name_i = new Label(0, i + 1,
						examineUsers.get(i).getUser_name() == null ? "" : examineUsers.get(i).getUser_name());
				Label real_name_i = new Label(1, i + 1,
						examineUsers.get(i).getReal_name() == null ? "" : examineUsers.get(i).getReal_name());
				Label frame_work_i = new Label(2, i + 1,
						examineUsers.get(i).getWhole_name() == null ? "" : examineUsers.get(i).getWhole_name());
				ws.addCell(user_name_i);
				ws.addCell(real_name_i);
				ws.addCell(frame_work_i);
			}
			// 写进文档
			wwb.write();
			// 关闭Excel工作簿对象
			wwb.close();
		} catch (Exception e) {
			logger.error("异常", e);
		} finally {
			if (os != null) {
				os.close();
			}
		}
		// 日志
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
		// AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
		// String operation = adminUserInfoByUuid.getUser_name() +
		// AdminCommon.COMMON_EXPORT + "测评任务未完成人员信息表";
		return null;
	}

	/**
	 * 根据uuid获取测评任务
	 *
	 * @param uuid 测评任务uuid
	 * @return 测评任务实体
	 */
	@RequestMapping("/findTableTaskByuuid")
	@ResponseBody
	public TenantTableTasks findTableTaskByuuid(String uuid) {
		TenantTableTasks entity = tenantTableTasksService.selectByPrimaryKey(uuid);
		return entity;
	}

	/**
	 * 根据条件获取获取测评任务
	 *
	 * @param framework_id
	 * @param table_uuid
	 * @param begin_time   "yyyy-MM-dd HH:mm:ss"
	 * @param end_time     "yyyy-MM-dd HH:mm:ss"
	 * @param admin_uuid
	 * @return
	 */
	@RequestMapping("/getAllTask")
	@ResponseBody
	public ResponseData getAllTask(Long framework_id, String table_uuid, String begin_time, String end_time,
			@RequestParam String admin_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<>();
		AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
		if (!StringUtils.isEmpty(table_uuid))
			map.put("tableUuid", table_uuid);
		getframeworkDatas(framework_id, adminUserInfoByUuid, map);
		if (begin_time != null && !"".equals(begin_time)) {
			map.put("beginTime", DateTimeUtil.getUtcFromStrings(begin_time));
		}
		if (end_time != null && !"".equals(end_time)) {
			map.put("endTime", DateTimeUtil.getUtcFromStrings(end_time));
		}
		try {
			List<Map<String, Object>> allTaskByMap = tenantTableTasksService.getAllTaskByMap(map);
			map.clear();
			map.put("list", allTaskByMap);
			mResponseData.setData(map);
		} catch (Exception e) {
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("获取失败");
		}
		return mResponseData;
	}

	/**
	 * 测评任务用户
	 *
	 * @param task_uuid
	 * @return
	 */
	@RequestMapping("/getUserByTaskUuid")
	@ResponseBody
	public ResponseData getUserByTaskUuid(Integer page, Integer page_size, String task_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isEmpty(task_uuid)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("任务id为空");
			return mResponseData;
		}
		map.put("task_uuid", task_uuid);

		try {
			PageInfo pi = new PageInfo();
			if (page != null && page_size != null) {
				pi.setCurrentPage(page);
				pi.setPageSize(page_size);
			}
			Long count = eUserService.listTableTaskUsersCount(map);
			List<EUser> list = eUserService.listTableTaskUsers(pi, map);
			for (EUser entity : list) {
				TenantFrameworks fra = tenantFrameworksService.getFrameworkById(entity.getFramework_id());
				if (fra != null) {
					String whole_Name = fra.getWhole_name();
					entity.setFramework_name(whole_Name);
				}
				map.clear();
				map.put("task_uuid", task_uuid);
				map.put("user_uuid", entity.getUuid());
				List<TenantTableTaskInfo> user_task_status = tenantTableTaskInfoService.findFinishedTableTask(map);
				if (user_task_status.size() > 0) {
					entity.setUser_task_status("1");
					entity.setTask_info_uuids(user_task_status.get(0).getUuids());
				}
			}
			TenantTableTasks tenantTableTasks = tenantTableTasksService.selectByPrimaryKey(task_uuid);
			if (tenantTableTasks.getUser_num() != null)
				if (count.intValue() != tenantTableTasks.getUser_num()) {
					tenantTableTasks.setUser_num(count.intValue());
					tenantTableTasksService.updateByPrimaryKey(tenantTableTasks);
				}
			map.clear();
			map.put("list", list);
			map.put("count", count);
			mResponseData.setData(map);
		} catch (Exception e) {
			logger.error("异常", e);
		}
		return mResponseData;
	}

	@RequestMapping("/showTaskDetail")
	@ResponseBody
	public ResponseData showTaskDetail(String task_uuid) {
		Map<String, Object> map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		if (StringUtils.isEmpty(task_uuid)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("task_uuid不能为空");
			return mResponseData;
		}
		map.put("task_uuid", task_uuid);
		List<TenantTableTasks> mTenantTableTasks = tenantTableTasksService.listAllTableTasks(new PageInfo(), map);

		if (mTenantTableTasks == null || mTenantTableTasks.size() == 0) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("无该问卷信息");
			return mResponseData;
		}
		String[] tableUuids = mTenantTableTasks.get(0).getTable_uuids().split(";");
		map.put("uuids", tableUuids);
		Long count = sysTableBriefService.findTaskTablesCount(map);
		List<SysTableBrief> list = sysTableBriefService.findTaskTables(map);
		map.clear();
		map.put("tenantTableTasks", mTenantTableTasks);
		map.put("list", list);
		map.put("count", count);
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 新建测量任务1步
	 *
	 * @return
	 */
	@RequestMapping("/addTaskNew")
	@ResponseBody
	public ResponseData addTaskNew(String task_name, Long publish_date, Integer report_status, String memo,
			String admin_uuid, String framework_ids, String user_uuids, String table_params, String table_alias,
			Integer addSon, Integer default_status) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser user = getAdminUserInfoByUuid(admin_uuid);
		try {
			if (default_status != null && default_status == 1) {
				long defaultTasksCount = tenantTableTasksService.findDefaultTasksCount(user.getFramework_id() + "");
				if (defaultTasksCount != 0) {
					mResponseData.setCode(-1);
					mResponseData.setMsg("测评信息录入失败！默认任务已存在！");
					return mResponseData;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		TenantTableTasks task = saveTenantTableTasksData(task_name, publish_date, report_status, memo, map, user,
				default_status);
		if (task == null) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("测评信息录入失败！");
			return mResponseData;
		}
		if (default_status == 0) { // 非默认任务进行人员添加
			mResponseData = addTaskUsers(task.getUuid(), framework_ids, addSon, user_uuids);
			if (mResponseData.getCode() == -1) {
				mResponseData.setCode(-1);
				mResponseData.setMsg("测评信息录入失败！");
				return mResponseData;
			}
		}
		mResponseData = submitTaskTables(task.getUuid(), table_params, user.getUuid(), table_alias, default_status);

		map.put("uuid", task.getUuid());
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 导出普通用户模板
	 * http://192.168.0.197:8094/cloud-customer/user/exUserTemplateXls?channel_id=scs20210873081475
	 *
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/exUserTemplate")
	public String exUserTemplateXls(String channel_id, HttpServletResponse response, String admin_uuid,
			Integer file_type) throws IOException {
		String fileName = "测评用户模板";
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		String type = "";
		if (file_type == null || file_type == 1) {
			type = ".xls";
		} else {
			type = ".xlsx";
		}
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + type).getBytes(), "iso-8859-1"));

		// 根据传进来的file对象创建可写入的Excel工作薄
		OutputStream os = response.getOutputStream();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> mlist = new ArrayList<>();

		mlist.add("用户名");
		try {
			WritableWorkbook wwb = null;
			// 创建可写入的Excel工作簿
			wwb = Workbook.createWorkbook(os);
			WritableSheet ws = wwb.createSheet("测评用户模板", 0);
			// 查询数据库中所有的数据
			List<Label> mlistLabel = new ArrayList<>();
			for (int i = 0; i < mlist.size(); i++) {
				mlistLabel.add(new Label(i, 0, mlist.get(i)));
			}
			// 要插入到的Excel表格的行号，默认从0开始
			for (int i = 0; i < mlistLabel.size(); i++) {
				ws.addCell(mlistLabel.get(i));
			}
			// 写进文档
			wwb.write();
			// 关闭Excel工作簿对象
			wwb.close();
		} catch (Exception e) {
			logger.error("异常", e);
		} finally {
			if (os != null) {
				os.close();
			}
		}
		return null;
	}

	@RequestMapping(value = "addTaskUserByExcel")
	@ResponseBody
	public ResponseData addTaskUserByExcel(String file, String admin_uuid, String task_name, Long publish_date,
			Integer report_status, String memo, String framework_ids, String user_uuids, String table_params,
			String table_alias, Integer addSon) {
		Map<String, Object> map = new HashMap<>();
		AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
		TenantTableTasks task = saveTenantTableTasksData(task_name, publish_date, report_status, memo, map,
				adminUserInfoByUuid, 0);

		ResponseData mResponseData = new ResponseData();
		List<String> frameworks = new ArrayList<String>();
		List<String> subtenants = new ArrayList<String>();
		List<String> mlist = new ArrayList<>();
		mlist.add("用户名");
		List<String> nameList = new ArrayList<>();
		try {
//            if (file == null || file.isEmpty()) {
//                mResponseData.setMsg("文件为空");
//                return mResponseData;
//            }
//            FileSaver fs = new FileSaver(file);
//            String localPath = fsg.generator(fs);

//            String localPath = "D://upload/1c28b648-8203-41d6-b691-3d0d85c21891.xlsx";
//            String localPath  = "http://hgkjyun.cn/pushresources/4/20210928101805/人员222.xlsx";
			String localPath = file;
			System.out.println("url=" + file);
			TaskUserExcelParseTool excelParseTool = new TaskUserExcelParseTool();
			excelParseTool.setFilePath(localPath, mlist);
			org.apache.poi.ss.usermodel.Workbook workbook = excelParseTool.initWorkBook();
			if (workbook != null) {
				excelParseTool.parseWorkbook(workbook);
			}
			if (!org.springframework.util.StringUtils.isEmpty(excelParseTool.errorMsg)) {
				mResponseData.setCode(-1);
				mResponseData.setMsg(excelParseTool.errorMsg);
				return mResponseData;
			}
			if (!org.springframework.util.StringUtils.isEmpty(excelParseTool.errorMsg)) {
				mResponseData.setCode(-1);
				mResponseData.setMsg(excelParseTool.errorMsg);
				return mResponseData;
			}
			if (excelParseTool.invalid_method) {
				mResponseData.setCode(-1);
				mResponseData.setMsg("EXCEL第一行字段名称有错误，请不要修改模板中的第一行字段信息");
				return mResponseData;
			} else {
				for (int i = 0; i < excelParseTool.mUserExcelList.size(); i++) {
					System.out.println(excelParseTool.mUserExcelList.get(i).getUser_name());
					nameList.add(excelParseTool.mUserExcelList.get(i).getUser_name());
				}
			}
			int count = 0;
			List<String> userUuids = new ArrayList<>();
			List<String> strings = new ArrayList<>();
			String channelId = adminUserInfoByUuid.getChannel_id();
			map.put("channel_id", channelId);
			for (int i = 0; i < nameList.size(); i++) {
				strings.add(nameList.get(i));
				if (nameList.size() % 2000 == 0) {
					map.put("user_name", strings);
					List<String> uuids = eUserService.listUserUuid(map);
					userUuids.addAll(uuids);
					System.out.println("strings=" + strings.size());
					System.out.println("longs=" + userUuids.size());
					strings = new ArrayList<>();
				}
			}
			if (strings.size() > 0) {
				map.put("user_name", strings);
				List<String> uuids = eUserService.listUserUuid(map);
				userUuids.addAll(uuids);
				System.out.println("strings=" + strings.size());
				System.out.println("longs=" + userUuids.size());
				strings = new ArrayList<>();
			}

			String prefix = "INSERT INTO tenant_table_task_info (uuid, task_uuid, user_uuid,task_status,enabled) VALUES ";
			Connection conn = null;
			PreparedStatement pst = null;
			SqlSession nativeSqlSession = null;
			try {
				// 保存sql后缀
				StringBuffer suffix = new StringBuffer();
				nativeSqlSession = getNativeSqlSession();
				conn = getConnection(nativeSqlSession);
				// 设置事务为非自动提交
				conn.setAutoCommit(false);
				// Statement st = conn.createStatement();
				// 比起st，pst会更好些
				pst = conn.prepareStatement(" ");
				// 外层循环，总提交事务次数
//                TenantTableTasks tabletask = tenantTableTasksService.findTableTaskByUuid(task_uuid);

				if (task.getFramework_tree() != null && !"".equals(task.getFramework_tree())) {
					String framework_tree = task.getFramework_tree();
					String[] trees = task.getFramework_tree().split("\\+");
					if (framework_tree.endsWith("+"))
						frameworks = new ArrayList<String>(Arrays.asList(trees[0].split("\\|")));
					else if (framework_tree.startsWith("+"))
						subtenants = new ArrayList<String>(Arrays.asList(trees[1].split("\\|")));
					else {
						frameworks = new ArrayList<String>(Arrays.asList(trees[0].split("\\|")));
						subtenants = new ArrayList<String>(Arrays.asList(trees[1].split("\\|")));
					}
				}
				if (userUuids.size() > 0) {
					for (int i = 0; i < userUuids.size(); i++) {
						suffix.append("(UUID() , '" + task.getUuid() + "' ,'" + userUuids.get(i) + "',"
								+ task.getStatus() + ", 1),");
						count++;
						if (count % 20000 == 0) { // 最大一次提交20000条数据
							// 构建完整sql
							String sql = prefix + suffix.substring(0, suffix.length() - 1);
							// 添加执行sql
							pst.addBatch(sql);
							// 执行操作
							pst.executeBatch();
							// 提交事务
							conn.commit();
							// 清空上一次添加的数据
							suffix = new StringBuffer();
						}
					}
					if (count % 20000 > 0) { // 将剩余的一起提交
						// 构建完整sql
						String sql = prefix + suffix.substring(0, suffix.length() - 1);
						// 添加执行sql
						pst.addBatch(sql);
						// 执行操作
						pst.executeBatch();
						// 提交事务
						conn.commit();
						// 清空上一次添加的数据
						suffix = new StringBuffer();
					}

					if (task.getUser_num() != null)
						task.setUser_num(task.getUser_num() + count);
					else
						task.setUser_num(count);

					String framework_tree = "";
					String subtenant_tree = "";
					for (int i = 0; i < frameworks.size(); i++) {
						if (i == 0)
							framework_tree += frameworks.get(i);
						else
							framework_tree += "|" + frameworks.get(i);
					}
					for (int i = 0; i < subtenants.size(); i++) {
						if (i == 0)
							subtenant_tree += subtenants.get(i);
						else
							subtenant_tree += "|" + subtenants.get(i);
					}
					if ("".equals(framework_tree) && "".equals(subtenant_tree))
						task.setFramework_tree("");
					else
						task.setFramework_tree(framework_tree + "+" + subtenant_tree);
					tenantTableTasksService.updateByPrimaryKeySelective(task);
					// 头等连接
					pst.close();
					conn.close();
				}
			} catch (Exception exception) {
				exception.printStackTrace();
				return null;
			} finally {
				IOclose(conn, pst, nativeSqlSession);
			}
			ResponseData responseData1 = submitTaskTables(task.getUuid(), table_params, adminUserInfoByUuid.getUuid(),
					table_alias, 0);
			map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			map.put("count", count);
			mResponseData.setData(map);
			return mResponseData;
		} catch (Exception e) {
			logger.error("异常", e);
		}
		mResponseData.setCode(500);
		mResponseData.setMsg("文件读取异常");
		return mResponseData;
	}

	private TenantTableTasks saveTenantTableTasksData(String task_name, Long publish_date, Integer report_status,
			String memo, Map<String, Object> map, AdminUser user, Integer default_status) {
		TenantTableTasks task = new TenantTableTasks();
		try {
			task.setName(task_name);
			task.setFramework_id(user.getFramework_id());
			task.setReport_status(report_status);
			task.setMemo(memo);
			task.setChannel_id(user.getChannel_id());
			if (default_status == null)
				default_status = 0;
			task.setDefault_status(default_status);
			task.setUser_num(0);

			// 随机获取任务图片

			Integer count = sysTaskImagesService.listPageTaskImagesCount(map);
			Random rand = new Random();
			Integer imageId = rand.nextInt(count) + 1;
			SysTaskImages taskImage = sysTaskImagesService.selectByPrimaryKey(imageId);
			if (taskImage != null) {
				task.setImage_url(taskImage.getImage_url());
			} else {
				List<SysTaskImages> list = sysTaskImagesService.listPageTaskImages(null, map);
				SysTaskImages taskImage2 = list.get(0);
				task.setImage_url(taskImage2.getImage_url());
			}
			task.setCreate_by(user.getUuid());
			task.setStatus(0);
			if (publish_date == null || publish_date == 0) {
				task.setPublish_date((new Date().getTime() / 1000) + 10);
			} else {
				task.setPublish_date(publish_date);
			}
			task.setCreate_date(new Date().getTime());
			tenantTableTasksService.insert(task);
		} catch (Exception e) {
			logger.error("异常", e);
			return null;
		}
		return task;
	}

	/**
	 * 添加任务测评人员
	 *
	 * @return
	 */

	public ResponseData addTaskUsers(String task_uuid, String framework_ids, Integer addSon, String user_uuids) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<>();
		int count = 0;
		List<Long> frameworkIds = new ArrayList<Long>();
		List<String> subtenants = new ArrayList<>();
		map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		String prefix = "INSERT INTO tenant_table_task_info (uuid, task_uuid, user_uuid,task_status,enabled) VALUES ";
		if (addSon == null)
			addSon = 0;
		try {
			// 保存sql后缀
			StringBuffer suffix = new StringBuffer();
			TenantTableTasks tabletask = tenantTableTasksService.selectByPrimaryKey(task_uuid);

			if (framework_ids != null && !"".equals(framework_ids)) {
				String[] args = framework_ids.split(",");
				for (int i = 0; i < args.length; i++) {
					Long aLong = Long.valueOf(args[i]);
					if (!frameworkIds.contains(aLong)) {
						frameworkIds.add(aLong);
					}
					if (addSon == 1) {
						frameworkIds.addAll(getAllSonTenantFrameworksId(Long.getLong(args[i])));
					}
				}
				Map<String, Object> p_map = new HashMap<String, Object>();
				p_map.put("framework_ids", frameworkIds);
				List<EUser> users = eUserService.listUsers(null, p_map);
				for (int j = 0; j < users.size(); j++) {
					suffix.append("(UUID() , '" + task_uuid + "' ,'" + users.get(j).getUuid() + "',"
							+ tabletask.getStatus() + ", 1),");
					count++;
				}
			} else if (user_uuids != null && !"".equals(user_uuids)) {
				String[] ids = user_uuids.split(",");
				for (int i = 0; i < ids.length; i++) {
					suffix.append("(UUID() , '" + task_uuid + "' ,'" + ids[i] + "'," + tabletask.getStatus() + ", 1),");
					count++;
				}
			}
			String sql = prefix + suffix.substring(0, suffix.length() - 1);
			jdbcTemplate.execute(sql);
			if (tabletask.getUser_num() != null)
				tabletask.setUser_num(tabletask.getUser_num() + count);
			else
				tabletask.setUser_num(count);
			String framework_tree = "";
			for (int i = 0; i < frameworkIds.size(); i++) {
				if (i == 0)
					framework_tree += frameworkIds.get(i);
				else
					framework_tree += "|" + frameworkIds.get(i);
			}

			if ("".equals(framework_tree))
				tabletask.setFramework_tree("");
			else
				tabletask.setFramework_tree(framework_tree);
			tabletask.setUser_num(count);
			tenantTableTasksService.updateByPrimaryKey(tabletask);
		} catch (Exception e) {
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("测评人员信息录入失败！");
			return mResponseData;
		}
		map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		map.put("count", count);
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 最后提交测评任务（包含添加量表）
	 *
	 * @return
	 */
	public ResponseData submitTaskTables(String task_uuid, String table_params, String admin_uuid, String table_alias,
			Integer default_status) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		ResponseData mResponseData = new ResponseData();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			TenantTableTasks tabletask = tenantTableTasksService.selectByPrimaryKey(task_uuid);

			List<String> keys = new ArrayList<>();
			List<String> aliakeys = new ArrayList<>();
			boolean setAlia = false;
			if (table_params.contains(",")) {
				String[] split = table_params.split(",");
				keys = Arrays.asList(split);
			} else {
				keys.add(table_params);
			}
			if (!StringUtils.isEmpty(table_alias)) {
				if (table_alias.contains("##")) {
					String[] split = table_alias.split("##");
					aliakeys = Arrays.asList(split);
				} else {
					aliakeys.add(table_alias);
				}
				if (keys.size() == aliakeys.size()) {
					setAlia = true;
				}
			}

			String table_uuids = "";
			for (int i = 0; i < keys.size(); i++) {
				table_uuids += keys.get(i) + ";";
			}
			int task_status = 2;

			if (default_status == 0) { // 非默认测评任务
				String prefix = "replace into tenant_table_task_info (uuid,task_uuid,user_uuid,table_uuid,table_alias,finished,task_status,report_status,cost_time,enabled) values ";

				try {
					// 保存sql后缀
					StringBuffer suffix = new StringBuffer();

					List<TenantTableTaskInfo> infos = tenantTableTaskInfoService.listTableTaskInfoByTaskUuid(task_uuid);
					// 外层循环，总提交事务次数
					for (int i = 0; i < keys.size(); i++) {
						SysTableBrief table = sysTableBriefService.findTableByUuid(keys.get(i));
						for (int j = 0; j < infos.size(); j++) {
							TenantTableTaskInfo info = infos.get(j);
							if (i == 0)
								suffix.append("('" + info.getUuid() + "','" + task_uuid + "','" + info.getUser_uuid()
										+ "','" + keys.get(i) + "','"
										+ (setAlia ? (aliakeys.get(i).equals("@") ? "" : aliakeys.get(i)) : "") + "',0,"
										+ task_status + "," + tabletask.getReport_status() + "," + table.getCost_time()
										+ ", 1),");
							else
								suffix.append("(UUID() ,'" + task_uuid + "','" + info.getUser_uuid() + "','"
										+ keys.get(i) + "','"
										+ (setAlia ? (aliakeys.get(i).equals("@") ? "" : aliakeys.get(i)) : "") + "',0,"
										+ task_status + "," + tabletask.getReport_status() + "," + table.getCost_time()
										+ ", 1),");
						}
					}
					String sql = prefix + suffix.substring(0, suffix.length() - 1);
					jdbcTemplate.execute(sql);
				} catch (Exception e) {
					logger.error("异常", e);
				}
			}
			table_uuids = table_uuids.substring(0, table_uuids.length() - 1);
			tabletask.setTable_uuids(table_uuids);
			tabletask.setStatus(task_status);
			AdminUser user = getAdminUserInfoByUuid(admin_uuid);
			tenantTableTasksService.updateByPrimaryKey(tabletask);
			map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			mResponseData.setData(map);
		} catch (Exception e) {
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("测评量表信息录入失败！");
			return mResponseData;
		}

		return mResponseData;
	}

	/**
	 * 添加任务测评人员
	 *
	 * @return
	 */
	@RequestMapping("/addTaskUsersFortaskUuid")
	@ResponseBody
	public ResponseData addTaskUsersFortaskUuid(String task_uuid, String framework_ids, String user_uuids,
			Integer addSon, String admin_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		int count = 0;
		List<Long> frameworkIds = new ArrayList<Long>();
		map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		String prefix = "replace into tenant_table_task_info (uuid,task_uuid,user_uuid,table_uuid,table_alias,finished,task_status,report_status,cost_time,enabled) values ";
		try {
			// 保存sql后缀
			StringBuffer suffix = new StringBuffer();
			// 外层循环，总提交事务次数
			TenantTableTasks tabletask = tenantTableTasksService.selectByPrimaryKey(task_uuid);

			List<String> keys = new ArrayList<String>();
			String table_params = tabletask.getTable_uuids();
			if (table_params.contains(";")) {
				String[] split = table_params.split(";");
				keys = Arrays.asList(split);
			} else {
				keys.add(table_params);
			}

			if (framework_ids != null && !"".equals(framework_ids)) {
				count = 0;
				String[] args = framework_ids.split("\\|");
				for (int i = 0; i < args.length; i++) {
					if (!frameworkIds.contains(Long.getLong(args[i]))) {
						frameworkIds.add(Long.getLong(args[i]));
					}
					if (addSon == 1) {
						frameworkIds.addAll(getAllSonTenantFrameworksId(Long.getLong(args[i])));
					}
				}
				Map<String, Object> p_map = new HashMap<>();
				p_map.put("framework_ids", frameworkIds);
				List<EUser> users = eUserService.listUsers(null, p_map);
				for (int i = 0; i < keys.size(); i++) {
					SysTableBrief table = sysTableBriefService.findTableByUuid(keys.get(i));
					for (int j = 0; j < users.size(); j++) {
						Map<String, Object> mapTemp = new HashMap<String, Object>();
						mapTemp.put("task_uuid", task_uuid);
						mapTemp.put("table_uuid", keys.get(i));
						mapTemp.put("user_uuid", users.get(j).getUuid());
						List<TenantTableTaskInfo> tableTaskInfo = tenantTableTaskInfoService.getTableTaskInfo(mapTemp);
						if (tableTaskInfo == null || tableTaskInfo.size() == 0) {
							suffix.append("(UUID() ,'" + task_uuid + "','" + users.get(j).getUuid() + "','"
									+ keys.get(i) + "','" + "" + "',0," + tabletask.getStatus() + ","
									+ tabletask.getReport_status() + "," + table.getCost_time() + ", 1),");
							count++;
						}

					}
				}
				if (keys.size() != 0)
					count = count / keys.size();
			} else {
				count = 0;
				for (int i = 0; i < keys.size(); i++) {
					SysTableBrief table = sysTableBriefService.findTableByUuid(keys.get(i));
					if (user_uuids != null && !"".equals(user_uuids)) {
						String[] ids = user_uuids.split(",");
						for (int j = 0; j < ids.length; j++) {
							Map<String, Object> mapTemp = new HashMap<String, Object>();
							mapTemp.put("task_uuid", task_uuid);
							mapTemp.put("table_uuid", keys.get(i));
							mapTemp.put("user_uuid", ids[j]);
							List<TenantTableTaskInfo> tableTaskInfo = tenantTableTaskInfoService
									.getTableTaskInfo(mapTemp);
							if (tableTaskInfo == null || tableTaskInfo.size() == 0) {
								suffix.append("(UUID() ,'" + task_uuid + "','" + ids[j] + "','" + keys.get(i) + "','"
										+ "" + "',0," + tabletask.getStatus() + "," + tabletask.getReport_status() + ","
										+ table.getCost_time() + ", 1),");
								count++;
							}
						}
					}
				}
				if (keys.size() != 0)
					count = count / keys.size();
			}
			if (suffix != null || suffix.length() != 0) {
				String sql = prefix + suffix.substring(0, suffix.length() - 1);
				jdbcTemplate.execute(sql);
				Integer user_num = tabletask.getUser_num();
				tabletask.setUser_num(user_num + count);
				String framework_tree = "";
				for (int i = 0; i < frameworkIds.size(); i++) {
					if (i == 0)
						framework_tree += frameworkIds.get(i);
					else
						framework_tree += "," + frameworkIds.get(i);
				}

				if ("".equals(framework_tree))
					tabletask.setFramework_tree("");
				else
					tabletask.setFramework_tree(framework_tree);
				tenantTableTasksService.updateByPrimaryKey(tabletask);
			}
		} catch (Exception e) {
			logger.error("异常", e);
		}
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 删除任务测评人员
	 *
	 * @return
	 */
	@RequestMapping("/deleteTaskUsers")
	@ResponseBody
	public ResponseData deleteTaskUsers(HttpServletRequest request, String task_uuid, String framework_ids,
			String user_uuids, String admin_uuid) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		Integer count = 0;
		List<String> frameworks = new ArrayList<String>();
		List<String> subtenants = new ArrayList<String>();
		if (StringUtils.isEmpty(task_uuid)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("任务信息为空");
			return mResponseData;
		}
		if (StringUtils.isEmpty(user_uuids) && StringUtils.isEmpty(framework_ids)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("未选择用户");
			return mResponseData;
		}
		TenantTableTasks tabletask = tenantTableTasksService.selectByPrimaryKey(task_uuid);
		if (tabletask.getFramework_tree() != null && !"".equals(tabletask.getFramework_tree())) {
			String framework_tree = tabletask.getFramework_tree();
			frameworks = new ArrayList<String>(Arrays.asList(framework_tree.split("\\|")));
		}
		if (framework_ids != null && !"".equals(framework_ids)) {
			String[] args = framework_ids.split(",");
			List<Long> ids = new ArrayList<Long>();
			for (int i = 0; i < args.length; i++) {
				if (frameworks.contains(args[i]))
					frameworks.remove(args[i]);
				ids.addAll(getAllSonTenantFrameworksId(Long.getLong(args[i])));
			}
			Map<String, Object> p_map = new HashMap<String, Object>();
			p_map.put("framework_ids", ids);
			p_map.put("task_uuid", task_uuid);
			List<EUser> users = eUserService.listTableTaskUsers(null, p_map);
			count = (int) eUserService.listTableTaskUsersCount(p_map);
			List<String> userIds = new ArrayList<String>();
			for (int j = 0; j < users.size(); j++) {
				userIds.add(users.get(j).getUuid());
			}
			if (userIds.size() > 0) {
				Map<String, Object> para_map = new HashMap<String, Object>();
				para_map.put("task_uuid", task_uuid);
				para_map.put("user_uuids", userIds);
				tenantTableTaskInfoService.deleteTableTaskInfo(para_map);
			}
		}

		if (user_uuids != null && !"".equals(user_uuids)) {
			String[] ids = user_uuids.split(",");
			for (int i = 0; i < ids.length; i++) {
				Map<String, Object> para_map = new HashMap<String, Object>();
				para_map.put("task_uuid", task_uuid);
				para_map.put("user_uuid", ids[i]);
				if (tenantTableTaskInfoService.deleteTableTaskInfo(para_map) != 0)
					count++;
			}
		}

		if (tabletask.getUser_num() != null)
			tabletask.setUser_num(tabletask.getUser_num() - count);
		String framework_tree = "";
		String subtenant_tree = "";
		for (int i = 0; i < frameworks.size(); i++) {
			if (i == 0)
				framework_tree += frameworks.get(i);
			else
				framework_tree += "|" + frameworks.get(i);
		}
		for (int i = 0; i < subtenants.size(); i++) {
			if (i == 0)
				subtenant_tree += subtenants.get(i);
			else
				subtenant_tree += "|" + subtenants.get(i);
		}
		if ("".equals(framework_tree) && "".equals(subtenant_tree))
			tabletask.setFramework_tree("");
		else
			tabletask.setFramework_tree(framework_tree + "+" + subtenant_tree);
		tenantTableTasksService.updateByPrimaryKey(tabletask);
		map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		map.put("count", count);
		mResponseData.setData(map);

		return mResponseData;
	}

	/**
	 * 删除报告
	 */
//    @RequestMapping(value = "/delReport", method = RequestMethod.POST)
	@RequestMapping(value = "/delReport")
	@ResponseBody
	public AjaxJson delReport(HttpServletRequest request, String ids, String admin_uuid) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		int delNum = 0;
		AjaxJson j = new AjaxJson();
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
		AdminUser user = getAdminUserInfoByUuid(admin_uuid);
		if (!StringUtils.isEmpty(ids)) {
			if (ids.contains("|")) {
				String[] args = ids.split("\\|");
				for (int i = 0; i < args.length; i++) {
					long cc = Long.valueOf(args[i]);
					try {
						tenantTableReportsService.deleteTableReport(cc);
						j.setSuccess(true);
						j.setMsg("删除成功！");
						String operation = user.getUser_name() + cc;
						/*
						 * TenantLogs tenantLogs = new TenantLogs();
						 * tenantLogs.setUser_id(user.getId());
						 * tenantLogs.setFramework_id(user.getTenant_id());
						 * tenantLogs.setModule("tb_task"); tenantLogs.setOperation(operation);
						 * tenantLogsService.insert(tenantLogs);
						 */
						delNum++;
					} catch (Exception e) {
						logger.error("异常", e);
						j.setSuccess(false);
						j.setMsg("删除失败！");
					}
				}
			} else {
				try {
					tenantTableReportsService.deleteTableReport(Long.valueOf(ids));
					j.setSuccess(true);
					j.setMsg("删除成功！");
					String operation = user.getUser_name() + ids;

					delNum++;
				} catch (NumberFormatException e) {
					logger.error("异常", e);
					j.setSuccess(false);
					j.setMsg("删除失败！");
				}
			}
		} else {
			j.setSuccess(false);
			j.setMsg("删除失败,参数为空！");
		}

		return j;
	}

	/**
	 * 导出所有的报告
	 *
	 * @return exportReportList
	 */
	@RequestMapping("/exportWord")
	@ResponseBody
	public ResponseData exportWord(HttpServletResponse response, HttpServletRequest request, Long framework_id,
			@RequestParam String admin_uuid, String user_name, String real_name, String table_uuid, String user_gender,
			String test_begin_date, String test_end_date, String report_level, String user_uuid) {
		Boolean waterMark = false; // 添加水印开关
		ResponseData responseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> p_map = new HashMap<String, Object>();
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
		AdminUser operator = getAdminUserInfoByUuid(admin_uuid);

		TenantFrameworks framework;
		List<String> report_levels = new ArrayList<>();
		if (!StringUtils.isEmpty(user_uuid))
			p_map.put("user_uuid", user_uuid);
		if (!StringUtils.isEmpty(user_name))
			p_map.put("user_name", user_name);
		p_map.put("searchName", user_name);
		if (!StringUtils.isEmpty(real_name))
			p_map.put("real_name", real_name);
		if (!StringUtils.isEmpty(table_uuid))
			p_map.put("table_uuid", table_uuid);
		if (!StringUtils.isEmpty(user_gender))
			p_map.put("user_gender", user_gender);
		framework = tenantFrameworksService.getFrameworkById(operator.getFramework_id());
		// docname = framework.getName();
		if (framework_id != null) {
			// docname = tenantFrameworksService.getFrameworkById(framework_id).getName();
		}
		getReportLevel(report_level, p_map, report_levels);
		getframeworkDatas(framework_id, operator, p_map);

		try {
			if (!StringUtils.isEmpty(test_begin_date)) {
				p_map.put("test_begin_date", DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
			}
			if (!StringUtils.isEmpty(test_end_date)) {
				p_map.put("test_end_date", DateTimeUtil.getEndUtcFromString(test_end_date) * 1000);
			}
			List<TenantTableReports> lists = tenantTableReportsService.listTableReportsByMap(null, p_map);
			if (lists == null || lists.size() == 0) {
				responseData.setMsg("无数据");
				responseData.setData(map);
				return responseData;
			}
			String downloadName = "测评报告";

			long downloadId = System.currentTimeMillis() / 1000;
			executor = new ThreadPoolExecutor(8, 20, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue());
			executor.execute(new Thread() {
				public void run() {
					String docname = "测评报告";
					try {
						logger.info("开始生成文件！文件处理中。。。");
						String shtml = "";
						String filename = "";
						String docpathtemp = docpath;
						// 如果不存在,创建文件夹
						File fdate1 = new File(docpathtemp);
						if (!fdate1.exists() && !fdate1.isDirectory()) {
							fdate1.mkdir();
						}
						// 建立日期为名的文件夹
						Date date = new Date();
						String pathdate = docpathtemp + String.valueOf(new SimpleDateFormat("yyyyMMdd").format(date));
						// 如果不存在,创建文件夹
						File fdate = new File(pathdate);
						if (!fdate.exists() && !fdate.isDirectory()) {
							fdate.mkdir();
						}
						docpathtemp = pathdate + "/";
						docname = docname + System.currentTimeMillis() / 1000;
						docname = URLDecoder.decode(docname + "-" + operator.getUser_name(), "UTF-8");
						for (int i = 0; i < lists.size(); i++) {
							shtml = "";
							String tempstr = "";
							tempstr = lists.get(i).getWhole_data();
							if (tempstr.indexOf("测评结果") == -1) {
								shtml += tempstr;
							} else {
								tempstr = convertStr(tempstr);
								shtml += tempstr;
							}
							shtml = shtml.replace("width=720border='0'", "width='100%'  border='0'");
							String sname = lists.get(i).getUser_name() + "-" + lists.get(i).getReal_name();
							String snameNew = sname + "_" + new SimpleDateFormat("yyyyMMdd").format(date);
							// 建立文件临时文件夹
							File folder = new File(docpathtemp + docname + "/");
							String filenameTemp = docpathtemp + docname + "/" + sname + ".docx";// 文件路径+名称+文件类型
							File file = new File(filenameTemp);
							// 如果文件夹不存在则创建    
							if (!folder.exists() && !folder.isDirectory()) {
								folder.mkdir();
							}
							// 如果文件不存在，则创建新的文件
							if (!file.exists()) {
								file.createNewFile();
								filename += sname + ";";
							} else if (!filename.contains(sname + ";")) {
								file.delete();
								file.createNewFile();
								filename += sname + ";";
							}
							// 写入报告
							writeFileContent(docpathtemp + docname + "/" + sname + ".docx", shtml);
							// 添加水印开关
							if (waterMark == true) {
								logger.info("--------------开始添加水印-----------");
								String originalSname = sname; // 原先docx 所在的位置
								sname = snameNew; // 添加水印后 docx 所在的位置
								WaterMarkUtil.addMarkStr(docpathtemp + docname + "/" + originalSname + ".docx",
										docpathtemp + docname + "/" + sname + ".docx", operator.getUser_name());
								logger.info("--------------添加水印成功 -----------" + docpathtemp + docname + "/" + sname
										+ ".docx");
							} else {
								logger.info("------水印开关关闭-----waterMark= " + waterMark);
							}
						}
						ZipUtils ss = new ZipUtils();
						ss.doCompress(docpathtemp + docname + "/", docpathtemp + docname + ".zip");
						// 压缩文件转化为数据流
						logger.info("获取文件成功！文件处理中。。。");
						File filedown = new File(docpathtemp + docname + ".zip");
//                        saveExportFile(filedown, framework, downloadId, downloadName, operator.getUuid());
					} catch (IOException e) {
						logger.info("获取文件失败！" + e.getMessage());
						logger.error("异常", e);
					}
				}
			});

			map.put("downloadId", downloadId);
			map.put("downloadName", downloadName);
			responseData.setData(map);

		} catch (Exception e) {
			logger.error("异常", e);
			responseData.setCode(-1);
			responseData.setMsg("获取文件失败！");
		}
		return responseData;
	}

	private void getReportLevel(String report_level, Map<String, Object> p_map, List<String> report_levels) {
		if (!StringUtils.isEmpty(report_level)) {
			if (report_level.contains(",")) {
				for (int k = 0; k < report_level.split(",").length; k++) {
					report_levels.add(report_level.split(",")[k]);
				}
			} else {
				report_levels.add(report_level);
			}
			p_map.put("report_levels", report_levels);
		}
	}

	/**
	 * 向文件中写入内容
	 *
	 * @param filepath 文件路径与名称
	 * @param newstr   写入的内容
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static boolean writeFileContent(String filepath, String newstr) throws IOException {
		Boolean bool = false;
		try {
			Document doc = new Document(filepath);
			String strtemp = doc.getFirstSection().toString(); // doc.FirstSection.Body.Paragraphs

			String stradd = strtemp + newstr;
			if (stradd.contains("com.aspose.words.Section@")) {
				Integer ss = stradd.indexOf("com.aspose.words.Section@");
				String substr = stradd.substring(ss, 33);
				String laststr = substr.substring(substr.length() - 1, substr.length());
				if (laststr.equals("<")) {
					substr = stradd.substring(ss, 32);
				}
				stradd = stradd.replaceAll(substr, " ");
			}

			DocumentBuilder docBuilder = new DocumentBuilder(doc);
			docBuilder.startTable();
			docBuilder.insertHtml(stradd);
			doc.save(filepath);
			bool = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bool;
	}

	/**
	 * 向文件中写入内容
	 *
	 * @param htmlstr 文件路径与名称
	 * @return
	 * @throws IOException
	 */
	public static String convertStr(String htmlstr) {
		String returnstr = "";
		try {
			/*
			 * if((htmlstr.indexOf("卡特尔16种个性测验")>0)||(htmlstr.indexOf("90项症状清单")>0)) {
			 */
			String[] args = htmlstr.split("测评结果");
			String[] results = args[1].split("'>");

			returnstr += args[0] + "测评结果" + results[0] + "'>";
			for (int i = 1; i < results.length - 1; i++) {
				char[] c = results[i].toCharArray();
				int count = 0;
				for (int j = 0; j < c.length; j++) {
					String len = Integer.toBinaryString(c[j]);
					if (len.length() > 8)
						count++;
				}
				int countall = count / 42;// 42
				if (countall > 0) {
					for (int k = 0; k < countall; k++) {
						String tempstr1 = results[i].substring(42 * k, 42 * k + 42);
						returnstr += tempstr1 + "<br />";
					}
					String tempstr2 = results[i].substring(42 * countall);
					returnstr += tempstr2 + "'>";
				} else {
					returnstr += results[i] + "'>";
				}
			}
			returnstr += results[results.length - 1];
			/*
			 * } else{ returnstr=htmlstr; }
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnstr;
	}

	/**
	 * 导出测评报告
	 *
	 * @param response
	 */
	@RequestMapping("/mydownload")
	public void export(HttpServletResponse response, String task_info_uuids, String htmlcontent, String user_name,
			@RequestParam String admin_uuid) {
		OutputStream os = null;
		try {
			String strhtml = "";
			String[] info_uuids = new String[0];
			if (!StringUtils.isEmpty(htmlcontent))
				info_uuids = htmlcontent.split(",");
			if (!StringUtils.isEmpty(task_info_uuids))
				info_uuids = task_info_uuids.split(",");
			for (int i = 0; i < info_uuids.length; i++) {
				Map<String, Object> report = tenantTableReportsService.getFullTableReportsByTaskInfoUuid(info_uuids[i]);
				String tempstr = "";
				tempstr = report.get("whole_data") + "<br/><br/><br/><br/>";
				if (tempstr.indexOf("测评结果") == -1) {
					strhtml += tempstr;
				} else {
					tempstr = convertStr(tempstr);
					strhtml += tempstr;
				}
			}
			strhtml = strhtml.replace("width=720border='0'", "width='100%' border='0'");
			strhtml = strhtml.replace("width='540'", "width='auto'");

			// 建立临时随机文件
			java.util.Date dt = new java.util.Date(System.currentTimeMillis());
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String fileName = fmt.format(dt);
			fileName = fileName + ".docx";

			String docurl = docpath;
			// 如果不存在,创建文件夹
			File fdate1 = new File(docurl);
			if (!fdate1.exists() && !fdate1.isDirectory()) {
				fdate1.mkdir();
			}
			File file = new File(docurl + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			writeFileContent(docurl + fileName, strhtml);
			os = response.getOutputStream();
			File filedown = new File(docurl + fileName);
			if (!filedown.exists()) {
				return;
			}
			response.reset();
			response.setHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("测评报告" + ".docx", "UTF-8"));
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.setContentType("application/octet-stream; charset=utf-8");
			os.write(FileUtils.readFileToByteArray(filedown));
			if (filedown.exists()) {
				filedown.delete();
			}
			AdminUser operator = getAdminUserInfoByUuid(admin_uuid);
			String operation = operator.getUser_name() + "导出普通用户报告到world文档:" + user_name;

			TenantLogs tenantLogs = new TenantLogs();
			tenantLogs.setUser_uuid(operator.getUuid());
			tenantLogs.setChannel_id(operator.getChannel_id());
			tenantLogs.setFramework_id(operator.getFramework_id());
			tenantLogs.setModule("dev_manage");
			tenantLogs.setOperation(operation);
			tenantLogsService.insert(tenantLogs);
			return;

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return;
	}

	/**
	 * 导出测评报告
	 *
	 * @param user_name
	 */
	@RequestMapping("/print")
	@ResponseBody
	public AjaxJson print(String user_name, String admin_uuid) {
		AjaxJson aj = new AjaxJson();
		try {
			aj.setSuccess(true);
			AdminUser operator = getAdminUserInfoByUuid(admin_uuid);
			String operation = operator.getUser_name() + "打印普通用户报告:" + user_name;

			TenantLogs tenantLogs = new TenantLogs();
			tenantLogs.setUser_uuid(operator.getUuid());
			tenantLogs.setChannel_id(operator.getChannel_id());
			tenantLogs.setFramework_id(operator.getFramework_id());
			tenantLogs.setModule("mark");
			tenantLogs.setOperation(operation);
			tenantLogsService.insert(tenantLogs);
			aj.setSuccess(true);
		} catch (Exception e) {
			aj.setSuccess(false);
			logger.error("异常", e);
		}
		return aj;
	}

	/**
	 * 删除测评任务
	 *
	 * @param uuid 任务uuid
	 * @return
	 */
	@RequestMapping("/updateTestTask")
	@ResponseBody
	public ResponseData updateTestTask(String uuid, String admin_uuid) {
		ResponseData mResponseData = new ResponseData();
		TenantTableTasks tableTask = tenantTableTasksService.selectByPrimaryKey(uuid);
		if (StringUtils.isEmpty(uuid)) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("任务 uuid  为空");
			return mResponseData;
		}
		if (StringUtils.isEmpty(admin_uuid)) {
			mResponseData.setMsg("任务 发布人  为空");
			return mResponseData;
		}
		if (tableTask != null) {
			tableTask.setStatus(5);
			tenantTableTasksService.updateByPrimaryKeySelective(tableTask);
		}

		return mResponseData;
	}

	/**
	 * 删除测评任务
	 *
	 * @param task_uuid 任务uuid
	 * @return
	 */
	@RequestMapping("/deleteTestTask")
	@ResponseBody
	public ResponseData deleteTestTask(String task_uuid) {
		ResponseData mResponseData = new ResponseData();
		try {
			// 报告总数
			Map<String, Object> map = new HashMap<>();
			map.put("groupFlag", 0);
			map.put("task_uuid", task_uuid);
			long reportCount = tenantTableReportsService.countTableReportFinished(map);
			long warningCount = tenantTableReportsService.countTableReportWarningByTaskUuid(map);
			TenantTableTasks tableTask = tenantTableTasksService.selectByPrimaryKey(task_uuid);
			tableTask.setStatus(4);
			tenantTableTasksService.updateByPrimaryKeySelective(tableTask);

		} catch (Exception e) {
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("删除失败");
		}
		return mResponseData;
	}

	/**
	 * 用户查看当前任务
	 *
	 * @return @throws
	 */
	@RequestMapping("/userTasks")
	@ResponseBody
	public ResponseData userTasks(HttpServletRequest request, String user_uuid, Integer page, Integer page_size,
			Integer type) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		List<TenantTableTasks> tasks = new ArrayList<TenantTableTasks>();
		map.put("user_uuid", user_uuid);
		if (type == null)
			type = 0;
		if (type == 0)
			map.put("unfinished", 1);
		else if (type == 1)
			map.put("finished", 1);
		PageInfo pi = new PageInfo();
		if (page != null && page_size != null) {
			pi.setCurrentPage(page);
			pi.setPageSize(page_size);
		}

		try {
			List<Map<String, Object>> info_maps = tenantTableTaskInfoService.listPageTableTaskInfos(pi, map);
			for (int i = 0; i < info_maps.size(); i++) {
				Map<String, Object> info_map = info_maps.get(i);
				TenantTableTasks task = tenantTableTasksService.findTableTaskByUuid((String) info_map.get("task_uuid"));
				task.setPercentage(String.valueOf(((BigDecimal) info_map.get("percentage")).intValue()));
				Map<String, Object> p_map = new HashMap<>();
				AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(task.getCreate_by());
				if (adminUserInfoByUuid == null) { // 专业账号删除后或者测试账号失效后无法搜索出来
					task.setCreate_name("无效账号");
				} else {
					task.setCreate_name(adminUserInfoByUuid.getReal_name());
				}
				tasks.add(task);
			}
			Map<String, Object> attr = new HashMap<String, Object>();
			attr.put("count", tenantTableTaskInfoService.listPageTableTaskInfosCount(map));
			attr.put("tasks", tasks);
			mResponseData.setData(attr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("获取失败");
			return mResponseData;
		}

		return mResponseData;
	}

	/**
	 * 用户查看当前任务的具体量表
	 *
	 * @return @throws
	 */
	@RequestMapping("/userTaskTests")
	@ResponseBody
	public ResponseData userTaskTests(HttpServletRequest request, String user_uuid, String task_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> taskInfos = new ArrayList<Map<String, Object>>();
		map.put("user_uuid", user_uuid);
		map.put("task_uuid", task_uuid);
		try {
			taskInfos = tenantTableTaskInfoService.listAllTableTaskInfos(map);
			int finish_count = 0;
			for (int i = 0; i < taskInfos.size(); i++) {
				Map<String, Object> info = taskInfos.get(i);
				if ("1".equals(info.get("finished"))) {
					info.put("answered_sum", info.get("question_sum"));
					finish_count++;
				} else if (info.get("answer") == null || "".equals(info.get("answer").toString()))
					info.put("answered_sum", 0);
				else {
					String[] args = info.get("answer").toString().split("\\|");
					info.put("answered_sum", args.length);
				}
			}
			Map<String, Object> attr = new HashMap<String, Object>();
			TenantTableTasks task = tenantTableTasksService.findTableTaskByUuid(task_uuid);
			task.setPercentage(String.valueOf(finish_count * 100 / taskInfos.size()));
			Map<String, Object> p_map = new HashMap<>();
			p_map.put("id", task.getCreate_by());
			AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(task.getCreate_by());
			if (adminUserInfoByUuid == null) { // 专业账号删除后或者测试账号失效后无法搜索出来
				task.setCreate_name("无效账号");
			} else {
				task.setCreate_name(adminUserInfoByUuid.getReal_name());
			}
			attr.put("task", task);
			attr.put("taskInfos", taskInfos);
			mResponseData.setData(attr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("获取失败");
			return mResponseData;
		}
		return mResponseData;
	}

	/**
	 * 新本答题数据提交
	 *
	 * @param
	 * @param index 当前提交题目的第一个序号
	 * @param value 当前所有选项 |分割
	 * @param times 当前所有时间 |分割
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/handleQuestion")
	@ResponseBody
	public ResponseData handleQuestion(String user_uuid, String task_info_uuid, Integer index, String value,
			String times) throws IOException {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		ResponseData mResponseData = new ResponseData();
		TenantTableTaskInfo info = tenantTableTaskInfoService.findTableTaskInfoByUuid(task_info_uuid);
		SysTableBrief table = sysTableBriefService.findTableByUuid(info.getTable_uuid());
		Map<String, Object> map = new HashMap<String, Object>();
		boolean isLast = false;
		String answer = info.getAnswer();
		String answer_seconds = info.getAnswer_seconds();
		Integer count = 0;
		if (value == null || value.equals("")) {
			map.put("answer", answer);
			map.put("answer_seconds", answer_seconds);
			mResponseData.setData(map);
			return mResponseData;
		} else {
			if (value.contains("\\||") || value.contains("||")) {
				mResponseData.setMsg("答题数据异常提交");
				mResponseData.setCode(-2);
				mResponseData.setData(map);
				return mResponseData;
			}
			if (times.contains("\\||") || times.contains("||")) {
				mResponseData.setMsg("答题数据异常提交");
				mResponseData.setCode(-2);
				mResponseData.setData(map);
				return mResponseData;
			}
			if (!StringUtils.isEmpty(times)) {
				int valueCount = value.split("\\|").length;
				int timesCount = times.split("\\|").length;
				if (valueCount != timesCount) {
					mResponseData.setMsg("答题数据异常提交");
					mResponseData.setCode(-2);
					mResponseData.setData(map);
					return mResponseData;
				}
			} else {
				mResponseData.setMsg("答题数据异常提交");
				mResponseData.setCode(-2);
				mResponseData.setData(map);
				return mResponseData;
			}
			if (value.contains("|")) {

				count = value.split("\\|").length - 1;
			} else {
				count = 0;
			}

			if ((index + count) - table.getQuestion_sum() > 0) {
				map.put("answer", answer);
				mResponseData.setCode(-2);
				info.setAnswer("");
				info.setAnswer_seconds("");
				info.setAnswer_time(0);
				info.setFinished(0);
				mResponseData.setMsg("答题数据重复提交");
				mResponseData.setData(map);
				return mResponseData;
			}

			// 特殊字符处理
			value.replace("&", "");
			value.replace("@", "");
			value.replace("，", ",");
			if (index == 1 || answer == null || "".equals(answer)) {
				info.setAnswer(value);
				info.setAnswer_seconds(times);
			} else {
				String[] arg = answer.split("\\|");
				String[] manswerSeconds = answer_seconds.split("\\|");
				if (arg.length == index - 1) {
					info.setAnswer(info.getAnswer() + "|" + value);
					info.setAnswer_seconds(info.getAnswer_seconds() + "|" + times);
				} else if (arg.length > index - 1) {
					String jion = "";
					String answerSeconds = "";
					for (int i = 0; i < index - 1; i++) {
						if (i == 0) {
							jion = arg[i];
							answerSeconds = manswerSeconds[i];
						} else {
							jion += "|" + arg[i];
							answerSeconds += "|" + manswerSeconds[i];
						}

					}
					info.setAnswer(jion + "|" + value);
					info.setAnswer_seconds(answerSeconds + "|" + times);
				} else if (arg.length < index - 1) {
					map.put("answer", answer);
					mResponseData.setCode(-2);
					info.setAnswer("");
					info.setAnswer_seconds("");
					info.setAnswer_time(0);
					info.setFinished(0);
					mResponseData.setMsg("部分答题数据丢失");
					mResponseData.setData(map);
					return mResponseData;
				}
				if ("Ppvt".equals(table.getEnglish_name())) {
					if ((index + count) >= 8) {
						String v_answer = info.getAnswer().substring(0, (index + count) * 2 - 1);
						String seconds = info.getAnswer_seconds();
						if (!ClsTest.getVerifyPPVT(v_answer)) {
							isLast = true;
							for (int i = (index + count) + 1; i <= table.getQuestion_sum(); i++) {
								v_answer += "|0";
								seconds += "|2";
							}
							info.setAnswer(v_answer);
							info.setFinished(1);
							info.setAnswer_seconds(seconds);
							Integer time = 0;
							if (seconds.contains("|")) {
								String[] mSeconds = seconds.split("\\|");
								for (int i = 0; i < mSeconds.length; i++) {
									time += Integer.parseInt(mSeconds[i]);
								}
							} else {
								time = Integer.parseInt(seconds);
							}
							info.setAnswer_time(time);
							tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
						}
					}
				}
			}

			if ((index + count) - table.getQuestion_sum() == 0) {
				String[] arg = info.getAnswer().split("\\|");
				if (table.getQuestion_sum() != arg.length) {
					mResponseData.setMsg("部分答题数据异常");
					mResponseData.setCode(-2);
					mResponseData.setData(map);
					return mResponseData;
				}
				isLast = true;
				info.setFinished(1);
				String seconds = info.getAnswer_seconds();
				Integer time = 0;
				if (seconds.contains("|")) {
					String[] mSeconds = seconds.split("\\|");
					for (int i = 0; i < mSeconds.length; i++) {
						time += Integer.parseInt(mSeconds[i]);
					}
				} else {
					time = Integer.parseInt(seconds);
				}
				info.setAnswer_time(time);
			}
			tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
		}
		if (isLast) {
			Integer answer_time = info.getAnswer_time();
			String[] split = info.getAnswer().split("\\|");
			Integer time = Double.valueOf(split.length * 1.2).intValue();
			if (answer_time < time) {
				mResponseData.setCode(-2);
				mResponseData.setMsg("经系统判定，答题过程中可能存在不认真作答的情况,请重新作答!");
				info.setAnswer("");
				info.setAnswer_seconds("");
				info.setAnswer_time(0);
				info.setFinished(0);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				return mResponseData;
			}
			// 去掉答案一致的无效判断
			/*
			 * List<String> ss = new ArrayList<String>(); for (String sss :
			 * info.getAnswer().replaceAll("[^0-9]", ",").split(",")) { if (sss.length() >
			 * 0) ss.add(sss); } List<String> collect =
			 * ss.stream().distinct().collect(Collectors.toList()); if (collect != null &&
			 * collect.size() == 1) { if (!collect.contains(1)) { mResponseData.setCode(-2);
			 * mResponseData.setMsg("经系统判定，答题过程中可能存在不认真作答的情况,请重新作答!"); info.setAnswer("");
			 * info.setAnswer_seconds(""); info.setAnswer_time(0); info.setFinished(0);
			 * tenantTableTaskInfoService.updateByPrimaryKeySelective(info); return
			 * mResponseData; } }
			 */
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("task_uuid", info.getTask_uuid());
			map2.put("user_uuid", info.getUser_uuid());
			List<TenantTableTaskInfo> finish_info = tenantTableTaskInfoService.findFinishedTableTask(map2);
			TenantTableTasks task = null;
			if (finish_info != null && finish_info.size() > 0) {
				task = tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid());
				if (task.getFinish_num() == null)
					task.setFinish_num(1);
				else
					task.setFinish_num(task.getFinish_num() + 1);
				Integer num = tenantTableTaskInfoService.countTaskFinishedUsers(info.getTask_uuid());
				task.setFinish_num(num);
				if (task.getStatus() != 6) {
					if (task.getFinish_num().equals(task.getUser_num())) // 所有人员完成测评
						task.setStatus(3);
				}
				tenantTableTasksService.updateByPrimaryKey(task);
			}
			logger.info("================答题完毕================");
			// 完成量表，以下计算结果因子
			EUser userInfoByUuid = getUserInfoByUuid(user_uuid);

			boolean generateFactorData = generateFactorData(table, userInfoByUuid, info);
			if (generateFactorData) {
				map2.clear();
				/*
				 * if (table.getUuid().equals("A6F2BDF7-F5D9-4310-8546-A5108E2136E1")) { if
				 * (aiHost != null && !aiHost.equals("")) { String aiReStr = HttpRequestUtil
				 * .sendGet(aiHost + "/cloud-ai/ai/generateOneAiReport?task_info_uuid=" +
				 * info.getUuid()); // //
				 * System.out.println("===============aiReStr==============="+aiReStr);
				 * map2.put("aiReStr", aiReStr); } }
				 */
				getTablemsgStr(info.getTable_uuid(), map2,
						task != null ? task.getFramework_id() : userInfoByUuid.getFramework_id());
				map2.put("task_info_uuid", task_info_uuid);
				mResponseData.setData(map2);

			} else {
				mResponseData.setCode(-1);
				mResponseData.setMsg("报告生成失败,请重新提交!");
				info.setFinished(0);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				tenantTableReportsService.deleteTableReportBytaskInfoUuid(info.getUuid());
			}
		}
		return mResponseData;
	}

	/**
	 * 新本答题数据提交 2022-07-12 按需求。将每次提交进行答案验证改为值验证最后一次
	 *
	 * @param
	 * @param value 当前所有选项 |分割
	 * @param times 当前所有时间 |分割
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/handleQuestionnew")
	@ResponseBody
	public ResponseData handleQuestionnew(String user_uuid, String task_info_uuid, String value, String times)
			throws IOException {
		ResponseData mResponseData = new ResponseData();
		TenantTableTaskInfo info = tenantTableTaskInfoService.findTableTaskInfoByUuid(task_info_uuid);
		if (info.getFinished() == 1) { // 当前测评已经被其他人做完，返回错误码
			mResponseData.setCode(0);
			mResponseData.setMsg("当前测评已经生成报告，可能有其他人登录了同一个账号完成了测评，请知悉！");
			return mResponseData;
		}
		SysTableBrief table = sysTableBriefService.findTableByUuid(info.getTable_uuid());
		Map<String, Object> map = new HashMap<String, Object>();
		boolean isLast = false;
		String answer = info.getAnswer();
		String answer_seconds = info.getAnswer_seconds();
		Integer count;
		if (value == null || value.equals("")) {
			map.put("answer", answer);
			map.put("answer_seconds", answer_seconds);
			mResponseData.setData(map);
			return mResponseData;
		}
		if (value.contains("|")) {
			count = value.split("\\|").length;
		} else {
			count = 0;
		}
		// 特殊字符处理
		value.replace("&", "");
		value.replace("@", "");
		value.replace("，", ",");
		info.setAnswer(value);
		info.setAnswer_seconds(times);

		if ("Ppvt".equals(table.getEnglish_name())) {
			if ((count) >= 9) {
				String v_answer = info.getAnswer().substring(0, (count) * 2 - 1);
				String seconds = info.getAnswer_seconds();
				if (!ClsTest.getVerifyPPVT(v_answer)) {
					isLast = true;
					for (int i = count; i <= table.getQuestion_sum(); i++) {
						v_answer += "|0";
						seconds += "|2";
					}
					info.setAnswer(v_answer);
					info.setFinished(1);
					info.setAnswer_seconds(seconds);
					Integer time = 0;
					if (seconds.contains("|")) {
						String[] mSeconds = seconds.split("\\|");
						for (int i = 0; i < mSeconds.length; i++) {
							time += Integer.parseInt(mSeconds[i]);
						}
					} else {
						time = Integer.parseInt(seconds);
					}
					info.setAnswer_time(time);
					tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				}
			}
		}
		logger.info("============isLast = true===============count" + count + "table.getQuestion_sum()="
				+ table.getQuestion_sum());
		if (count - table.getQuestion_sum() == 0) {
			isLast = true;
			logger.info("============ isLast = true===============");
			info.setFinished(1);
			Integer time = 0;
			if (times.contains("|")) {
				String[] mSeconds = times.split("\\|");
				for (int i = 0; i < mSeconds.length; i++) {
					time += Integer.parseInt(mSeconds[i]);
				}
			} else {
				time = Integer.parseInt(times);
			}
			info.setAnswer_time(time);
		}

		if (isLast) {
			logger.info("============isLast===============");
			if ((count - table.getQuestion_sum()) > 0 || value.contains("||") || times.contains("||")) {
				map.put("answer", answer);
				mResponseData.setCode(-2);
				info.setAnswer("");
				info.setAnswer_seconds("");
				info.setAnswer_time(0);
				info.setFinished(0);
				mResponseData.setMsg("答题数据出现异常，已帮您重置数据，请重新作答！");
				mResponseData.setData(map);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				return mResponseData;
			}

			if (!StringUtils.isEmpty(times)) {
				int valueCount = value.split("\\|").length;
				int timesCount = times.split("\\|").length;
				if (valueCount != timesCount) {
					map.put("answer", answer);
					mResponseData.setCode(-2);
					info.setAnswer("");
					info.setAnswer_seconds("");
					info.setAnswer_time(0);
					info.setFinished(0);
					mResponseData.setMsg("答题数据出现异常，已帮您重置数据，请重新作答！");
					mResponseData.setData(map);
					tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
					return mResponseData;
				}
			} else {
				map.put("answer", answer);
				mResponseData.setCode(-2);
				info.setAnswer("");
				info.setAnswer_seconds("");
				info.setAnswer_time(0);
				info.setFinished(0);
				mResponseData.setMsg("答题数据出现异常，已帮您重置数据，请重新作答！");
				mResponseData.setData(map);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				return mResponseData;
			}
			Integer answer_time = info.getAnswer_time();
			String[] split = info.getAnswer().split("\\|");
			Integer time = Double.valueOf(split.length * 1.2).intValue();
			if (answer_time < time) {
				mResponseData.setCode(-2);
				mResponseData.setMsg("经系统判定，答题过程中可能存在不认真作答的情况,请重新作答!");
				info.setAnswer("");
				info.setAnswer_seconds("");
				info.setAnswer_time(0);
				info.setFinished(0);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				return mResponseData;
			}
			Map<String, Object> map2 = new HashMap<String, Object>();
			logger.info("================答题完毕================");
			// 完成量表，以下计算结果因子
			EUser userInfoByUuid = getUserInfoByUuid(user_uuid);

			boolean generateFactorData = generateFactorData(table, userInfoByUuid, info);
			if (generateFactorData) {
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				map2.clear();
				TenantTableTasks task = tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid());
				getTablemsgStr(info.getTable_uuid(), map2,
						task != null ? task.getFramework_id() : userInfoByUuid.getFramework_id());
				map2.put("task_info_uuid", task_info_uuid);
				mResponseData.setData(map2);
				Map<String, Object> Newmap = new HashMap<String, Object>();
				Newmap.put("task_uuid", task.getUuid());
				Long userCount = eUserService.listTableTaskUsersCount(Newmap);
				int finishedCount = tenantTableTaskInfoService.getUserTaskInfoFinishedCount(Newmap);
				if (task.getUser_num() != null) {
					if (userCount.intValue() != task.getUser_num()) {
						task.setUser_num(userCount.intValue());
						logger.info("---修改User_num-- 成功 User_num: " + userCount.intValue());
					}
					if (task.getFinish_num() == null || finishedCount != task.getFinish_num()) {
						task.setFinish_num(finishedCount);
						logger.info("---修改Finish_num-- 成功 Finish_num: " + finishedCount);
					}
					if (userCount == finishedCount) // 全部完成
						task.setStatus(3);
					tenantTableTasksService.updateByPrimaryKey(task);
				}
			} else {
				mResponseData.setCode(-1);
				mResponseData.setMsg("报告生成失败,请重新提交!");
				String substringa = info.getAnswer().substring(0, info.getAnswer().lastIndexOf("|"));
				String substrings = info.getAnswer_seconds().substring(0, info.getAnswer_seconds().lastIndexOf("|"));
				info.setAnswer(substringa);
				info.setAnswer_seconds(substrings);
				info.setFinished(0);
				tenantTableTaskInfoService.updateByPrimaryKeySelective(info);
				tenantTableReportsService.deleteTableReportBytaskInfoUuid(info.getUuid());
				tenantTableReportsAttachedService.deleteByTaskInfoUUid(info.getUuid());
			}
		}
		return mResponseData;
	}

	private void getTablemsgStr(@RequestParam String table_uuid, Map<String, Object> tmap, Long framework_id) {
		
	}

	/**
	 * 答题完毕，生成因子数据
	 * */
	private boolean generateFactorData(SysTableBrief table, EUser user, TenantTableTaskInfo info) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		Long reportId = null;
		ClsAnswerRequest request = new ClsAnswerRequest();
		request.setType(table.getEnglish_name());
		request.setUuid(user.getUuid());
		if (user.getUser_gender() != null)
			request.setSex(user.getUser_gender());
		else {
			request.setSex(AdminCommon.DEFAULT_MALE);
		}
		TenantFrameworks frameworkById = tenantFrameworksService.getFrameworkById(user.getFramework_id());
		request.setScl(frameworkById.getScl());
		if (user.getUser_birth() != null)
			request.setAge(DateTimeUtil.getFloatAgeByBirthday(user.getUser_birth()));
		request.setAnswer(info.getAnswer());
		request.setAnswer_seconds(info.getAnswer_seconds());
		ClsAnswerResult result = ClsTest.getAnswer(request);
		logger.info("================计算结果完毕================" + result);
		if (result != null && "".equals(result.getMessage())) {
			// String inStr = "education"
			String resultString = ClsTest.getResultObjectString(result);
			/* 存储报告数据，包括因子字符串 */
			TenantTableReports report = new TenantTableReports();
			report.setTask_info_uuid(info.getUuid());
			report.setFactor_json(resultString);
			report.setUser_uuid(info.getUser_uuid());
			report.setTable_uuid(info.getTable_uuid());
			TenantFrameworks framework = tenantFrameworksService.getFrameworkById(user.getFramework_id());
			user.setFramework_name(framework.getWhole_name());
			info.setChinese_name(table.getChinese_name());
			info.setEnglish_name(table.getEnglish_name());
			/* 调用拼报告数据的函数 */
			ClsReport clsReport = new ClsReport();
			clsReport.setTableService(sysTableBriefService, mSysTableContentService, mSysTableDiagnosisService);
			ClsReportResult reportResult = clsReport.getReports(info, user, resultString);
			logger.info("================拼接报告完毕================" + reportResult);
			if ("".equals(reportResult.getMessage())) {
				Connection conn = null;
				PreparedStatement pst = null;
				SqlSession nativeSqlSession = null;
				try {
					report.setSimple_data(reportResult.getReport_simple());
					/* report.setNormal_data(reportResult.getReport_normal()); */
					report.setWhole_data(reportResult.getReport_complete());
					report.setReport_level(reportResult.getReport_level());
					report.setReport_prompt(reportResult.getReport_prompt());
					report.setDate(System.currentTimeMillis());

					String prefix = "insert into tenant_table_reports (task_info_uuid,  report_level,report_prompt, date, enabled, user_uuid, table_uuid  ) VALUES";

					// 保存sql后缀
					StringBuffer suffix = new StringBuffer();

					suffix.append("( '" + info.getUuid() + "','" + reportResult.getReport_level() + "' ,'"
							+ reportResult.getReport_prompt() + "' ,'" + System.currentTimeMillis() + "' ,1,'"
							+ info.getUser_uuid() + "','" + info.getTable_uuid() + "');");

					String prefixattached = "insert into tenant_table_reports_attached (task_info_uuid, factor_json, simple_data, whole_data ,enabled) VALUES";
					StringBuffer suffixattached = new StringBuffer();
					suffixattached.append("( '" + info.getUuid() + "' ,'" + resultString + "','"
							+ encodeHtmlString(reportResult.getReport_simple()) + "','"
							+ encodeHtmlString(reportResult.getReport_complete()) + "',1);");

					String prefix2 = "insert into tenant_table_factors (task_info_uuid, factor_name, factor_value ) VALUES ";
					/* 存储具体因子数据 */
					JSONObject jasonObject = JSONObject.fromObject(resultString);
					Map<String, String> map = (Map) jasonObject;

					String sql = "";
					StringBuffer suffix2 = new StringBuffer();
					if (map.size() > 0) {
						for (Map.Entry<String, String> entry : map.entrySet()) {
							TenantTableFactors factor = new TenantTableFactors();
							factor.setTask_info_uuid(info.getUuid());
							factor.setFactor_name(entry.getKey());
							if (entry.getValue() instanceof String)
								factor.setFactor_value(entry.getValue());
							else
								factor.setFactor_value(String.valueOf(entry.getValue()));
							suffix2.append("( '" + factor.getTask_info_uuid() + "' ,'" + factor.getFactor_name() + "','"
									+ factor.getFactor_value() + " '),");
						}
					}
					nativeSqlSession = getNativeSqlSession();
					conn = getConnection(nativeSqlSession);
					// 设置事务为非自动提交
					conn.setAutoCommit(false);

					pst = conn.prepareStatement(" ");
					pst.addBatch(prefix + suffix);
					pst.addBatch(prefixattached + suffixattached);
					if (suffix2.length() > 1)
						pst.addBatch(prefix2 + suffix2.substring(0, suffix2.length() - 1));
					pst.executeBatch();
					conn.commit();
					logger.info("================生成报告完毕================" + result);

				} catch (Exception e) {
					/*
					 * info.setFinished(0);
					 * 
					 * TenantTableTasks task =
					 * tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid()); if
					 * (task.getFinish_num() == null || task.getFinish_num() == 0)
					 * task.setFinish_num(0); else task.setFinish_num(task.getFinish_num() - 1);
					 * Integer num =
					 * tenantTableTaskInfoService.countTaskFinishedUsers(info.getTask_uuid());
					 * task.setFinish_num(num); if (task.getStatus() != 6) { task.setStatus(2); }
					 * tenantTableTasksService.updateByPrimaryKey(task);
					 */
					logger.error("================生成报告失败================", e);
					return false;
				} finally {
					IOclose(conn, pst, nativeSqlSession);

				}
				/* Scl90自动生成方案 */
				try {
					if ("Scl90".equals(table.getEnglish_name())) {
						ClsFaqMsg faqMsg = (ClsFaqMsg) result.getFaq_msg();
						generateSchemeFromTable(table, user, faqMsg, info);
					}
				} catch (Exception e) {
					logger.error("异常", e);
				}
				try {
					if ("Scl90".equals(table.getEnglish_name())) {
						String infoAnswer = info.getAnswer();
						Integer[] tt = { 1, 12, 27, 42, 52 }; // 疼痛 1.12.27.42.52
						Integer[] stbs = { 4, 40, 48, 49, 53, 56, 58 }; // 身体不适 4.40.48.49.53.56.58
						Integer[] bhq = { 41, 37 }; // 自卑 41 不合群 37
						Integer[] phcd = { 63, 67 };// 破坏冲动 63.67
						Integer[] sm = { 44, 64, 66 };// 失眠 44 64 66
						Integer[] ysyc = { 19, 60 }; // 饮食异常 19 60
						if (infoAnswer != null) {
							String[] split = infoAnswer.split("\\|");
							for (Integer aTt : tt) {
								Integer an = Integer.parseInt(split[aTt - 1]);
								if (an >= 3) {
									setExtTableScl(info, "1");
									break;
								}
							}
							for (Integer stb : stbs) {
								Integer an = Integer.parseInt(split[stb - 1]);
								if (an >= 3) {
									setExtTableScl(info, "2");
									break;
								}
							}
							for (Integer aBhq : bhq) {
								Integer an = Integer.parseInt(split[aBhq - 1]);
								if (an >= 3) {
									setExtTableScl(info, "3");
									break;
								}
							}
							for (Integer aPhcd : phcd) {
								Integer an = Integer.parseInt(split[aPhcd - 1]);
								if (an >= 3) {
									setExtTableScl(info, "4");
									break;
								}
							}
							for (Integer aSm : sm) {
								Integer an = Integer.parseInt(split[aSm - 1]);
								if (an >= 3) {
									setExtTableScl(info, "5");
									break;
								}
							}
							for (Integer aYsyc : ysyc) {
								Integer an = Integer.parseInt(split[aYsyc - 1]);
								if (an >= 3) {
									setExtTableScl(info, "6");
									break;
								}
							}
						}
					}
					logger.info("================90报告计算因子================");
				} catch (Exception e) {
					logger.error("异常", e);
				}
				return true;
			} else {
				/*
				 * TenantTableTasks task =
				 * tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid()); if
				 * (task.getFinish_num() == null || task.getFinish_num() == 0)
				 * task.setFinish_num(0); else task.setFinish_num(task.getFinish_num() - 1);
				 * Integer num =
				 * tenantTableTaskInfoService.countTaskFinishedUsers(info.getTask_uuid());
				 * task.setFinish_num(num); if (task.getStatus() != 6) { task.setStatus(2); }
				 * tenantTableTasksService.updateByPrimaryKey(task);
				 */
				logger.info("================拼接报告失败================" + reportResult);
				return false;
			}
		} else {
			return false;
		}

	}

	private void setExtTableScl(TenantTableTaskInfo info, String isTT) {
		ExtTableScl mExtTableScl = new ExtTableScl();
		mExtTableScl.setTaskUuid(info.getTask_uuid());
		mExtTableScl.setTableCode("Scl90");
		mExtTableScl.setUserUuid(info.getUser_uuid());
		mExtTableScl.setBodyMind(isTT);
		mExtTableSclService.insert(mExtTableScl);
	}

	/**
	 * 量表（Scl90）自动生成方案 因子等级为0表示正常，faqpair 90转70时如果faq_uuid为空，表示精神性
	 */
	private void generateSchemeFromTable(SysTableBrief table, EUser user, ClsFaqMsg faqMsg, TenantTableTaskInfo info) {
		TenantTableTasks task = tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid());
		TenantSchemes scheme = new TenantSchemes();
		scheme.setUser_uuid(user.getUuid());
		scheme.setChannel_id(user.getChannel_id());
		scheme.setFramework_id(user.getFramework_id());
		scheme.setLevel(faqMsg.getFaq_level());
		scheme.setCreate_type(0);
		scheme.setCreate_by(task.getCreate_by());
		scheme.setTask_info_uuid(info.getUuid());
		scheme.setDate(new Date().getTime());
		scheme.setIs_suggest(0);
		Map<String, Object> p_map = new HashMap<String, Object>();
		p_map.put("table_uuid", table.getUuid());
		p_map.put("table_sort", faqMsg.getSort());
		SysFaqPair faqPair = mSysFaqPairService.getFaqPairByMap(p_map);
		// 因子等级为0表示正常
		if (faqMsg.getFactor_level() == 0) {
			scheme.setDescription("SCL90的测试结果显示您心理状况良好。");
			scheme.setConsult_method("无。");
			scheme.setQuestion("无");
			scheme.setDaily_suggest("无。");
			mTenantSchemesService.insert(scheme);
		} else if (faqPair.getFaq_uuid() == null) { // faq_uuid为空，表示精神性，需转介
			scheme.setDescription("SCL90的测试结果显示您自觉有" + faqPair.getTable_rename() + "。");
			scheme.setConsult_method("鉴于您当前的心理状态，建议心理咨询辅导人员采取转介到专业机构进行复查或治疗。");
			scheme.setDaily_suggest("建议进行专业检查，遵医嘱服药或进行相关治疗。");
			scheme.setQuestion(faqPair.getTable_rename());
			mTenantSchemesService.insert(scheme);
		} else {
			TenantTableTasks tenantTableTasks = tenantTableTasksService.findTableTaskByUuid(info.getTask_uuid());
			if (tenantTableTasks != null) {
				AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(tenantTableTasks.getCreate_by());
				SysFaq faq = mSysFaqService.getFaqByUuid(faqPair.getFaq_uuid());
//                generateSchemeFromQuestion(user, adminUserInfoByUuid, faq, faqMsg.getFaq_level(), 0, task.getCreate_by(), info.getUuid(),
//                        faqPair.getTable_rename(), faqMsg.getFactor_level(), faqMsg.getFactor_name());
			}

		}
	}

	/**
	 * 获取量表所有题目和选项
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/getTableAllInfos")
	@ResponseBody
	public ResponseData getTableAllInfos(String task_info_uuid) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> map = new HashMap<String, Object>();
		TableAllInfo mTableAllInfo = new TableAllInfo();
		String mAnswerStr = "";
		String mAnswerSecondsStr = "";
		try {
			TenantTableTaskInfo info = tenantTableTaskInfoService.findTableTaskInfoByUuid(task_info_uuid);
			if (info == null) {
				mResponseData.setMsg("ID错误");
				mResponseData.setCode(-1);
				return mResponseData;
			}
			mAnswerStr = info.getAnswer();
			mAnswerSecondsStr = info.getAnswer_seconds();
			List<Map<String, Object>> mTableAllInfos = sysTableBriefService
					.findTableAllInfosByTableUuid(info.getTable_uuid());
			List<QuestionInfos> qtList = new ArrayList();
			List<String> sortList = new ArrayList();

			if (mTableAllInfos != null && mTableAllInfos.size() != 0) {
				for (int i = 0; i < mTableAllInfos.size(); i++) {
					mTableAllInfo.setDescription(mTableAllInfos.get(i).get("description").toString());
					mTableAllInfo.setGuide(mTableAllInfos.get(i).get("guide").toString());
					mTableAllInfo.setUuid(mTableAllInfos.get(i).get("table_uuid").toString());
					if (!sortList.contains(mTableAllInfos.get(i).get("sort").toString())) {
						sortList.add(mTableAllInfos.get(i).get("sort").toString());
						QuestionInfos mQuestionInfos = new QuestionInfos();
						mQuestionInfos.setQuestionTitle(mTableAllInfos.get(i).get("question").toString());
						mQuestionInfos.setTitle1(mTableAllInfos.get(i).get("title1").toString());
						mQuestionInfos.setTitle2(mTableAllInfos.get(i).get("title2").toString());
						mQuestionInfos.setAudioUrl(mTableAllInfos.get(i).get("audio_url") == null ? ""
								: mTableAllInfos.get(i).get("audio_url").toString());
						mQuestionInfos.setqStyle(mTableAllInfos.get(i).get("q_style").toString());
						qtList.add(mQuestionInfos);
					}
				}
			}
			if (sortList.size() < 1) {
				mResponseData.setMsg("获取题目失败,请稍后再试!");
				mResponseData.setCode(-1);
				return mResponseData;
			}
			List<QuestionInfos> mquestionList = new ArrayList();
			Map<String, List<Map<String, Object>>> stringListMap = new HashMap<>();
			for (int i = sortList.size() - 1; i >= 0; i--) {
				List<Map<String, Object>> tempList = new ArrayList<>();
				for (int k = mTableAllInfos.size() - 1; k >= 0; k--) {
					if (sortList.get(i).equals(mTableAllInfos.get(k).get("sort").toString())) {
						tempList.add(0, mTableAllInfos.get(k));
						mTableAllInfos.remove(k);
					}
				}
				stringListMap.put(sortList.get(i), tempList);
			}
			for (int i = 0; i < sortList.size(); i++) {
				List<Map<String, Object>> tempList = (List<Map<String, Object>>) stringListMap.get(sortList.get(i));
				QuestionInfos mQuestionInfo = new QuestionInfos();
				mQuestionInfo = qtList.get(i);
				List<QuestionAnswersInfos> anList = new ArrayList();
				List<String> score_a = new ArrayList();
				for (int k = 0; k < tempList.size(); k++) {
					if (!score_a.contains(tempList.get(k).get("score_a").toString())) {
						score_a.add(tempList.get(k).get("score_a").toString());
						QuestionAnswersInfos mQuestionAnswersInfos = new QuestionAnswersInfos();
						mQuestionAnswersInfos.setAnswers(tempList.get(k).get("answer_a") == null ? ""
								: tempList.get(k).get("answer_a").toString());
						mQuestionAnswersInfos.setaStyle(tempList.get(k).get("a_style").toString());
						mQuestionAnswersInfos.setPattern(tempList.get(k).get("a_pattern") == null ? ""
								: tempList.get(k).get("a_pattern").toString());
						mQuestionAnswersInfos.setText(tempList.get(k).get("a_ptext") == null ? ""
								: tempList.get(k).get("a_ptext").toString());
						mQuestionAnswersInfos.setImageUrl(tempList.get(k).get("image_url") == null ? ""
								: tempList.get(k).get("image_url").toString());
						List<QuestionAnswersInfos> bnList = new ArrayList();
						// mTableAllInfos.get(k).get("answer_uuid")
						if (tempList.get(k).get("answer_b") != null)
							for (int g = 0; g < tempList.size(); g++) {
								if (sortList.get(i).equals(tempList.get(g).get("sort").toString()) && tempList.get(k)
										.get("score_a").toString().equals(tempList.get(g).get("score_a").toString())) {
									QuestionAnswersInfos mQuestionAnswersInfosB = new QuestionAnswersInfos();
									mQuestionAnswersInfosB.setAnswers(tempList.get(g).get("answer_b") == null ? ""
											: tempList.get(g).get("answer_b").toString());
									mQuestionAnswersInfosB.setaStyle(tempList.get(g).get("b_style").toString());
									mQuestionAnswersInfos.setPattern(tempList.get(k).get("b_pattern") == null ? ""
											: tempList.get(k).get("b_pattern").toString());
									mQuestionAnswersInfos.setText(tempList.get(k).get("b_ptext") == null ? ""
											: tempList.get(k).get("b_ptext").toString());
									bnList.add(mQuestionAnswersInfosB);
								}
							}
						mQuestionAnswersInfos.setAnswersB(bnList);
						anList.add(mQuestionAnswersInfos);
					}
				}
				mQuestionInfo.setAnswers(anList);
				mquestionList.add(mQuestionInfo);
			}
			mTableAllInfo.setQuestionInfos(mquestionList);
			map.put("mTableAllInfo", mTableAllInfo);
			map.put("mAnswerStr", mAnswerStr);
			map.put("mAnswerSecondsStr", mAnswerSecondsStr);
			mResponseData.setData(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("异常", e);
			mResponseData.setCode(-1);
			return mResponseData;
		}
		return mResponseData;
	}

	/*
	 * if (sortList.get(i).equals(mTableAllInfos.get(k).get("sort").toString())) {
	 * if (!score_a.contains(mTableAllInfos.get(i).get("score_a").toString())) {
	 * score_a.add(mTableAllInfos.get(k).get("score_a").toString());
	 * QuestionAnswersInfos mQuestionAnswersInfos = new QuestionAnswersInfos();
	 * mQuestionAnswersInfos.setAnswers(mTableAllInfos.get(k).get("answer_a") ==
	 * null ? "" : mTableAllInfos.get(k).get("answer_a").toString());
	 * mQuestionAnswersInfos.setaStyle(mTableAllInfos.get(k).get("a_style").toString
	 * ()); mQuestionAnswersInfos.setImageUrl(mTableAllInfos.get(k).get("image_url")
	 * == null ? "" : mTableAllInfos.get(k).get("image_url").toString());
	 * 
	 * List<QuestionAnswersInfos> bnList = new ArrayList(); //
	 * mTableAllInfos.get(k).get("answer_uuid") if
	 * (mTableAllInfos.get(k).get("answer_b") != null) for (int g = 0; g <
	 * mTableAllInfos.size(); g++) { if
	 * (sortList.get(i).equals(mTableAllInfos.get(g).get("sort").toString()) &&
	 * mTableAllInfos.get(k).get("score_a").toString().equals(mTableAllInfos.get(g).
	 * get("score_a").toString())) { QuestionAnswersInfos mQuestionAnswersInfosB =
	 * new QuestionAnswersInfos();
	 * mQuestionAnswersInfosB.setAnswers(mTableAllInfos.get(k).get("answer_b") ==
	 * null ? "" : mTableAllInfos.get(k).get("answer_b").toString());
	 * mQuestionAnswersInfosB.setaStyle(mTableAllInfos.get(k).get("b_style").
	 * toString()); bnList.add(mQuestionAnswersInfosB); } }
	 * mQuestionAnswersInfos.setAnswersB(bnList); anList.add(mQuestionAnswersInfos);
	 * } }
	 */

	/**
	 * 用户查看当前测评报告
	 *
	 * @return @throws
	 */
	@RequestMapping("/viewTableReport")
	@ResponseBody
	public ResponseData viewTableReport(String task_info_uuids) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		Map<String, Object> map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		String result = "";
		if (task_info_uuids == null) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("uuids为空");
		} else {
			try {
				String[] info_uuids = task_info_uuids.split("\\|");
				for (int i = 0; i < info_uuids.length; i++) {
					TenantTableReportsAttached report = tenantTableReportsAttachedService
							.findTableReportByUuid(info_uuids[i]);
					if (report != null)
						result += report.getSimpleData() + "<br/><br/><br/><br/>";
				}

				map.put("html", result);
				mResponseData.setData(map);
			} catch (Exception e) {
				logger.error("异常", e);
			}
		}
		return mResponseData;
	}

	/**
	 * 咨询师查看测评报告
	 *
	 * @return @throws
	 */
	@RequestMapping("/viewNormalTableReport")
	@ResponseBody
	public ResponseData viewNormalTableReport(@RequestParam String task_info_uuids, String wholeData,
			String restoreSign) {
		// restoreSign 还原原来报告的标志
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		Map<String, Object> map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		String result = "";
		if (task_info_uuids == null) {
			mResponseData.setCode(-1);
			mResponseData.setMsg("uuids为空");
		} else {
			try {
				/*
				 * 3个模块调用 1.只有测评报告查询 task_info_uuids传入 2.测评报告编辑后进行保存 (编辑) task_info_uuids
				 * wholeData（最新的测评数据html） 传入 wholeData！=null 3.测评报告还原最初数据 task_info_uuids
				 * restoreSign（还原标标志） restoreSign!=null
				 */
				if (wholeData != null || restoreSign != null) { // 测评报告编辑以后进行保存 先将原先的数据备份到backend字段（只备份一次，备份最原始的数据
																// 【还原数据时使用backend字段】），在修改wholeData
					TenantTableReportsAttached taskreport = tenantTableReportsAttachedService
							.findTableReportByUuid(task_info_uuids);
					if (restoreSign != null) {
						// 还原原先的报告
						if (taskreport.getBackend() != null) {// 还原的时候 1.判断Backend是否为null(null 没有被修改过) 2.（Backend！=null）
																// Backend赋值->WholeData 再把Backend=null
							taskreport.setWholeData(taskreport.getBackend());
							taskreport.setBackend(null);
							logger.info("数据进行还原!");
						} else {
							mResponseData.setCode(-1);
							mResponseData.setMsg("该测评为最原始的数据报告！");
							return mResponseData;
						}
					} else { // 测评报告编辑后进行保存
						if (taskreport.getBackend() == null || "".equals(taskreport.getBackend())) {// 编辑时候判断是否是第一次修改
																									// (第一次修改时
																									// Backend=null)
																									// 1.第一次修改
																									// WholeData赋值->Backend
																									// 2.修改 WholeData
							taskreport.setBackend(taskreport.getWholeData());
							logger.info("第一次编辑测评数据!");
						}
					}
					if (restoreSign == null) { // 编辑的时候 （没有传入还原字段{restoreSign}）
						taskreport.setWholeData(wholeData);
					}
					tenantTableReportsAttachedService.updateByPrimaryKeyWithBLOBs(taskreport);
					logger.info("------修改wholeData的html成功");
				}
				String[] info_uuids = task_info_uuids.split("\\|");
				for (int i = 0; i < info_uuids.length; i++) {
					TenantTableReportsAttached report = tenantTableReportsAttachedService
							.findTableReportByUuid(info_uuids[i]);
					if (report != null) {
						result += report.getWholeData() + "<br/><br/><br/><br/>";
					}
				}
				map.put("html", result);
				mResponseData.setData(map);
			} catch (Exception e) {
				logger.error("异常", e);
			}
		}
		return mResponseData;
	}

	/**
	 * 咨询师查看测评报告
	 *
	 * @return @throws
	 */
	@RequestMapping("/viewUserAllNormalTableReport")
	@ResponseBody
	public ResponseData viewUserAllNormalTableReport(@RequestParam(required = true) String user_uuid) {
		String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
		Map<String, Object> map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		String result = "";
		map.put("user_uuid", user_uuid);
		List<TenantTableTaskInfo> tenantTableTaskInfos = tenantTableTaskInfoService.listUserFinishedTaskInfos(null,
				map);
		try {
			for (int i = 0; i < tenantTableTaskInfos.size(); i++) {
				TenantTableReportsAttached report = tenantTableReportsAttachedService
						.findTableReportByUuid(tenantTableTaskInfos.get(i).getUuid());
				if (report != null) {
					result += report.getWholeData() + "<br/><br/><br/><br/>";
				}
			}
			map.put("html", result);
			mResponseData.setData(map);
		} catch (Exception e) {
			logger.error("异常", e);
		}

		return mResponseData;
	}

	@RequestMapping("/scl90")
	@ResponseBody
	public ResponseData scl90() {

		Map<String, Object> map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		map.put("table_uuid", "A6F2BDF7-F5D9-4310-8546-A5108E2136E1");
		map.put("finished", "1");
		List<TenantTableTaskInfo> tableTaskInfo = tenantTableTaskInfoService.getTableTaskInfo(map);
		for (int i = 0; i < tableTaskInfo.size(); i++) {
			TenantTableTaskInfo info = tableTaskInfo.get(i);
			String infoAnswer = info.getAnswer();
			Integer[] tt = { 1, 12, 27, 42, 52 }; // 疼痛 1.12.27.42.52
			Integer[] stbs = { 4, 40, 48, 49, 53, 56, 58 }; // 身体不适 4.40.48.49.53.56.58
			Integer[] bhq = { 41, 37 }; // 自卑 41 不合群 37
			Integer[] phcd = { 63, 67 };// 破坏冲动 63.67
			Integer[] sm = { 44, 64, 66 };// 失眠 44 64 66
			Integer[] ysyc = { 19, 60 }; // 饮食异常 19 60
			if (infoAnswer != null) {
				String[] split = infoAnswer.split("\\|");
				for (Integer aTt : tt) {
					Integer an = Integer.parseInt(split[aTt - 1]);
					if (an >= 3) {
						setExtTableScl(info, "1");
						break;
					}
				}
				for (Integer stb : stbs) {
					Integer an = Integer.parseInt(split[stb - 1]);
					if (an >= 3) {
						setExtTableScl(info, "2");
						break;
					}
				}
				for (Integer aBhq : bhq) {
					Integer an = Integer.parseInt(split[aBhq - 1]);
					if (an >= 3) {
						setExtTableScl(info, "3");
						break;
					}
				}
				for (Integer aPhcd : phcd) {
					Integer an = Integer.parseInt(split[aPhcd - 1]);
					if (an >= 3) {
						setExtTableScl(info, "4");
						break;
					}
				}
				for (Integer aSm : sm) {
					Integer an = Integer.parseInt(split[aSm - 1]);
					if (an >= 3) {
						setExtTableScl(info, "5");
						break;
					}
				}
				for (Integer aYsyc : ysyc) {
					Integer an = Integer.parseInt(split[aYsyc - 1]);
					if (an >= 3) {
						setExtTableScl(info, "6");
						break;
					}
				}
			}
		}
		return mResponseData;
	}

	/**
	 * 用户查看有报告的测评列表
	 *
	 * @return @throws
	 */
	@RequestMapping("/personalTableReportList")
	@ResponseBody
	public ResponseData personalTableReportList(String user_uuid, String user_name, String real_name, String table_uuid,
			String test_begin_date, String test_end_date, String report_level, Integer page, Integer pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> p_map = new HashMap<String, Object>();
		ResponseData mResponseData = new ResponseData();
		if (!StringUtils.isEmpty(user_uuid))
			p_map.put("user_uuid", user_uuid);
		if (!StringUtils.isEmpty(table_uuid))
			p_map.put("table_uuid", table_uuid);
		if (!StringUtils.isEmpty(report_level))
			p_map.put("report_level", report_level);
		if (!StringUtils.isEmpty(test_begin_date)) {
			p_map.put("test_begin_date", DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
			System.out.println("test_begin_date=" + DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
		}
		if (!StringUtils.isEmpty(test_end_date)) {
			p_map.put("test_end_date", DateTimeUtil.getEndUtcFromString(test_end_date) * 1000);
			System.out.println("test_end_date=" + DateTimeUtil.getUtcFromString(test_end_date) * 1000);
		}
		PageInfo pi = new PageInfo();
		if (page == null || page == 0)
			page = 1;
		if (pageSize == null || pageSize == 0)
			pageSize = 10;
		pi.setCurrentPage(page);
		pi.setPageSize(pageSize);

		long listcount = tenantTableReportsService.listTableReportsByMapCount(p_map);
		List<TenantTableReports> lists = tenantTableReportsService.listTableReportsPcByMap(pi, p_map);
		map.put("lists", lists);
		map.put("listSize", listcount);
		mResponseData.setData(map);
		return mResponseData;
	}

	/**
	 * 导出测评报告答题数据
	 * http://192.168.0.197:8094/cloud-customer/testTask/excelListTableReports?admin_uuid=bace9880-f674-11eb-bc14-00163e1269b6&table_uuid=A6F2BDF7-F5D9-4310-8546-A5108E2136E1
	 * 答题数据导出
	 *
	 * @param response
	 * @param request
	 * @param user_uuid
	 * @param file_type       1xls 2xlsx
	 * @param user_name
	 * @param real_name
	 * @param table_uuid
	 * @param user_gender
	 * @param framework_id
	 * @param test_begin_date
	 * @param test_end_date
	 * @param report_level
	 * @param admin_uuid
	 */
	@RequestMapping("/excelListTableReports")
	@ResponseBody
	public void excelListTableReportsByMap(HttpServletResponse response, HttpServletRequest request, String user_uuid,
			Integer file_type, String user_name, String real_name, @RequestParam String table_uuid, String user_gender,
			Long framework_id, String test_begin_date, String test_end_date, String report_level,
			@RequestParam String admin_uuid) {
		Map<String, Object> p_map = new HashMap<String, Object>();
		AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
		String fileName = "";
		if (framework_id != null) {
			fileName = tenantFrameworksService.getFrameworkById(framework_id).getName();
		} else {
			fileName = tenantFrameworksService.getFrameworkById(adminUserInfoByUuid.getFramework_id()).getName();
		}
		fileName += "测评报告答题数据";
		getframeworkDatas(framework_id, adminUserInfoByUuid, p_map);
//        List<ExtFieldRecord> channelExtFieldRecord = getChannelExtFieldRecord(framework_id, adminUserInfoByUuid);
		List<String> report_levels = new ArrayList<>();
		if (!StringUtils.isEmpty(user_uuid))
			p_map.put("user_uuid", user_uuid);
		if (!StringUtils.isEmpty(user_name))
			p_map.put("user_name", user_name);
		p_map.put("searchName", user_name);
		if (!StringUtils.isEmpty(real_name))
			p_map.put("real_name", real_name);
		if (!StringUtils.isEmpty(table_uuid))
			p_map.put("table_uuid", table_uuid);
		if (!StringUtils.isEmpty(user_gender))
			p_map.put("user_gender", user_gender);
		if (!StringUtils.isEmpty(report_level)) {
			if (report_level.contains(",")) {
				report_levels.addAll(Arrays.asList(report_level.split(",")));
			} else {
				report_levels.add(report_level);
			}
			p_map.put("report_levels", report_levels);
		}
		if (!StringUtils.isEmpty(test_begin_date)) {
			p_map.put("test_begin_date", DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
			System.out.println("test_begin_date=" + DateTimeUtil.getUtcFromString(test_begin_date) * 1000);
		}
		if (!StringUtils.isEmpty(test_end_date)) {
			p_map.put("test_end_date", DateTimeUtil.getEndUtcFromString(test_end_date) * 1000);
			System.out.println("test_end_date=" + DateTimeUtil.getUtcFromString(test_end_date) * 1000);
		}
		List<Map<String, Object>> lists;
		lists = getTableReportsByTableId(table_uuid, p_map);
		if (lists != null && !lists.isEmpty()) {

			// 根据传进来的file对象创建可写入的Excel工作薄
			OutputStream os = null;
			try {
				response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				if (file_type == null || file_type == 1) {
					response.setHeader("Content-Disposition",
							"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
				} else {
					response.setHeader("Content-Disposition",
							"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
				}
				os = response.getOutputStream();
//                getExcelByTableId(table_uuid, lists, os, channelExtFieldRecord);

			} catch (Exception e) {
				logger.error("异常", e);
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private void getExcelByTableId(String table_uuid, List<Map<String, Object>> lists, OutputStream os,
			List<ExtFieldRecord> channelExtFieldRecord) throws Exception {
		switch (table_uuid) {
		case "62814CC1-6458-4B6B-9123-25246EEF8121":// 明尼苏达多相人格测验 566
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "566", channelExtFieldRecord);
			break;
		case "59651DE3-28B5-4947-8C22-71059AA3B34E":// 明尼苏达多相人格测验 399
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "399", channelExtFieldRecord);
			break;
		case "72141F13-F699-417F-B5F1-ECD0928DA88C":// 匹茨堡睡眠质量指数 (PSQI)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "PSQI", channelExtFieldRecord);
			break;
		case "C498C4AC-E1D4-4A49-ABF5-68BC9A73F0CD":// 社交焦虑量表 (LSAS)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "LSAS", channelExtFieldRecord);
			break;
		case "E7360A6B-DBD0-4271-8018-4D8A469205FD":// Yale—Brown强迫评定量表 (Y-BOCS)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "YBOCS", channelExtFieldRecord);
			break;
		case "B3819B35-396C-49AF-A382-F1FD5891B567":// 艾森克个性测验(儿童) (EPQ)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "EPQC", channelExtFieldRecord);
			break;
		case "7E39268B-A8A8-4837-ABD8-4109EE0CB1FE":// 艾森克个性测验(成人) (EPQ
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "EPQD", channelExtFieldRecord);
			break;
		case "422A1523-95CF-420C-9D4E-5119FE387F35":// 卡特尔16种个性测验 (16PF)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "16PF", channelExtFieldRecord);
			break;
		case "3CAC2EA7-F90E-442B-8EE6-BB865ACC46B9":// 躁狂量表 (BRMS)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "BRMS", channelExtFieldRecord);
			break;
		case "7111F968-61BB-4573-8FB8-5F10F8BF75EB":// 焦虑自评量表（SAS）
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "SAS", channelExtFieldRecord);
			break;
		case "37404F75-7DC3-4EDF-AF04-3C2D5723AF67":// 抑郁自评量表（SDS）
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "SDS", channelExtFieldRecord);
			break;
		case "E853E08A-1EDC-468C-9D64-AD0D7FA1093B":// 健康状况问卷 (SF-36)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "SF36", channelExtFieldRecord);
			break;
		case "F722ED89-BC6A-4DE5-B26F-050E2AF7788D":// 简明精神病量表 (BPRS)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "BPRS", channelExtFieldRecord);
			break;
		case "9DA86AE7-4BF3-4E2A-A80B-B4EC73F22E9B":// 简易智力状态检查 (CMMSE)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "CMMSE", channelExtFieldRecord);
			break;
		case "98E0C18B-789B-401E-920F-5DD44CCD9C38":// 汉密顿焦虑量表（HAMA）
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "HAMA", channelExtFieldRecord);
			break;
		case "2B169CE6-2E58-43AD-A55D-06480518859A":// 汉密顿抑郁量表 (HAMD)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "HAMD", channelExtFieldRecord);
			break;
		case "A6F2BDF7-F5D9-4310-8546-A5108E2136E1":// 90项症状清单 (SCL90)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "SCL90", channelExtFieldRecord); // 第十五题答案 : 选项 可信度:
																									// 不可信 可信
			break;
		case "93457D08-05B2-4425-8AED-D100BA9F49DC":// 公安民警应激生活事件调查表(Shirritant)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Shirritant", channelExtFieldRecord); //
			break;
		case "1639109E-2ABA-4917-A5AA-83790FD8C00A":// 生活事件量表
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Les", channelExtFieldRecord); //
			break;
		case "5BAE3F83-62F0-4324-862A-0C9715AE4576":// 青少年生活事件量表(Aslec)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Aslec", channelExtFieldRecord);
			break;
		case "CDCF43DA-E528-4D07-B90D-34DB681C130D":// 多动症诊断量表(Adhd)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Adhd", channelExtFieldRecord);
			break;
		case "22B9ECA4-08CD-4BAE-83EB-0ABBA63F5BE5":// 中国中学生心理健康检测(Xljk)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Xljk", channelExtFieldRecord);
			break;
		case "A0E5BB44-9BDF-4289-8780-910879F506B4":// 中学生学习动机调查表(Xxdj)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Xxdj", channelExtFieldRecord);
			break;
		case "C21A5598-F640-4699-9CA6-B35C84E2A808":// 考试行为困扰心理测查(Ksxwkl)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Ksxwkl", channelExtFieldRecord);
			break;
		case "D8DAC9DC-1DB3-4579-B7F1-F256CB49DB5D":// 中学生自信心困扰检测(Zbxl)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Zbxl", channelExtFieldRecord);
			break;
		case "88ECF8E5-60F7-4D9D-8E96-3E328F7C6B9D":// 中学生在校适应能力诊断(Zxsynl)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Zxsynl", channelExtFieldRecord);
			break;
		case "98C5350E-13B2-43EC-AA36-794312D47D4E":// 小学生心理健康综合测量(Xxxljkzh)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Xxxljkzh", channelExtFieldRecord);
			break;
		case "ED2A35EE-622A-4513-9A21-7218C8777555":// 中学生心理健康综合测量(Zxxljkzh)
			ExcleTableCreateUtil.getExcleTableDetails(lists, os, "Zxxljkzh", channelExtFieldRecord);
			break;
		default:
			ExcleTableCreateUtil.getExcel(lists, os, channelExtFieldRecord);
			break;
		}
	}

	private List<Map<String, Object>> getTableReportsByTableId(String table_uuid, Map<String, Object> p_map) {
		List<Map<String, Object>> lists;
		switch (table_uuid) {
		case "62814CC1-6458-4B6B-9123-25246EEF8121":// 明尼苏达多相人格测验 566
			lists = tenantTableReportsService.excelListTableReportsDetailsByMap(p_map);
			break;
		case "59651DE3-28B5-4947-8C22-71059AA3B34E":// 明尼苏达多相人格测验 566
			lists = tenantTableReportsService.excelListTableReportsDetailsByMap2(p_map);
			break;
		case "72141F13-F699-417F-B5F1-ECD0928DA88C":// 匹茨堡睡眠质量指数 (PSQI)
			lists = tenantTableReportsService.excelListTableReportsDetailsForPSQI(p_map);
			break;
		case "C498C4AC-E1D4-4A49-ABF5-68BC9A73F0CD":// 社交焦虑量表 (LSAS)
			lists = tenantTableReportsService.excelListTableReportsDetailsForLSAS(p_map);
			break;
		case "E7360A6B-DBD0-4271-8018-4D8A469205FD":// Yale—Brown强迫评定量表 (Y-BOCS)
			lists = tenantTableReportsService.excelListTableReportsDetailsForYBOCS(p_map);
			break;
		case "B3819B35-396C-49AF-A382-F1FD5891B567":// 艾森克个性测验(儿童) (EPQ)
			lists = tenantTableReportsService.excelListTableReportsDetailsForEPQC(p_map);
			break;
		case "7E39268B-A8A8-4837-ABD8-4109EE0CB1FE":// 艾森克个性测验(成人) (EPQ
			lists = tenantTableReportsService.excelListTableReportsDetailsForEPQA(p_map);
			break;
		case "422A1523-95CF-420C-9D4E-5119FE387F35":// 卡特尔16种个性测验 (16PF)
			lists = tenantTableReportsService.excelListTableReportsDetailsFor16PF(p_map);
			break;
		case "3CAC2EA7-F90E-442B-8EE6-BB865ACC46B9":// 躁狂量表 (BRMS)
			lists = tenantTableReportsService.excelListTableReportsDetailsForBRMS(p_map);
			break;
		case "7111F968-61BB-4573-8FB8-5F10F8BF75EB":// 焦虑自评量表（SAS）
			lists = tenantTableReportsService.excelListTableReportsDetailsForSAS(p_map);
			break;
		case "37404F75-7DC3-4EDF-AF04-3C2D5723AF67":// 抑郁自评量表（SDS）
			lists = tenantTableReportsService.excelListTableReportsDetailsForSDS(p_map);
			break;
		case "E853E08A-1EDC-468C-9D64-AD0D7FA1093B":// 健康状况问卷 (SF-36)
			lists = tenantTableReportsService.excelListTableReportsDetailsForSF36(p_map);
			break;
		case "F722ED89-BC6A-4DE5-B26F-050E2AF7788D":// 简明精神病量表 (BPRS)
			lists = tenantTableReportsService.excelListTableReportsDetailsForBPRS(p_map);
			break;
		case "9DA86AE7-4BF3-4E2A-A80B-B4EC73F22E9B":// 简易智力状态检查 (CMMSE)
			lists = tenantTableReportsService.excelListTableReportsDetailsForCMMSE(p_map);
			break;
		case "98E0C18B-789B-401E-920F-5DD44CCD9C38":// 汉密顿焦虑量表（HAMA）
			lists = tenantTableReportsService.excelListTableReportsDetailsForHAMA(p_map);
			break;
		case "2B169CE6-2E58-43AD-A55D-06480518859A":// 汉密顿抑郁量表 (HAMD)
			lists = tenantTableReportsService.excelListTableReportsDetailsForHAMD(p_map);
			break;
		case "A6F2BDF7-F5D9-4310-8546-A5108E2136E1":// 90项症状清单 (SCL90)
			lists = tenantTableReportsService.excelListTableReportsDetailsForSCL90(p_map);
			break;
		case "93457D08-05B2-4425-8AED-D100BA9F49DC":// 公安民警应激生活事件调查表(Shirritant)
			lists = tenantTableReportsService.excelListTableReportsDetailsForShirritant(p_map);
			break;
		case "1639109E-2ABA-4917-A5AA-83790FD8C00A":// 公安民警应激生活事件调查表(Shirritant)
			lists = tenantTableReportsService.excelListTableReportsDetailsForLes(p_map);
			break;
		case "5BAE3F83-62F0-4324-862A-0C9715AE4576":// 青少年生活事件量表(Aslec)
			lists = tenantTableReportsService.excelListTableReportsDetailsForAslec(p_map);
			break;
		case "CDCF43DA-E528-4D07-B90D-34DB681C130D":// 多动症诊断量表(Adhd)
			lists = tenantTableReportsService.excelListTableReportsDetailsForAdhd(p_map);
			break;
		case "22B9ECA4-08CD-4BAE-83EB-0ABBA63F5BE5":// 中国中学生心理健康检测(Xljk)
			lists = tenantTableReportsService.excelListTableReportsDetailsForXljk(p_map);
			break;
		case "A0E5BB44-9BDF-4289-8780-910879F506B4":// 中学生学习动机调查表(Xxdj)
			lists = tenantTableReportsService.excelListTableReportsDetailsForXxdj(p_map);
			break;
		case "C21A5598-F640-4699-9CA6-B35C84E2A808":// 考试行为困扰心理测查(Ksxwkl)
			lists = tenantTableReportsService.excelListTableReportsDetailsForKsxwkl(p_map);
			break;
		case "D8DAC9DC-1DB3-4579-B7F1-F256CB49DB5D":// 中学生自信心困扰检测(Zbxl)
		case "88ECF8E5-60F7-4D9D-8E96-3E328F7C6B9D":// 中学生在校适应能力诊断(Zxsynl)
			lists = tenantTableReportsService.excelListTableReportsDetailsForTotal(p_map);
			break;
		case "98C5350E-13B2-43EC-AA36-794312D47D4E":// 小学生心理健康综合测量(Xxxljkzh)
			lists = tenantTableReportsService.excelListTableReportsDetailsForXxxljkzh(p_map);
			break;
		case "ED2A35EE-622A-4513-9A21-7218C8777555":// 中学生心理健康综合测量(Zxxljkzh)
			lists = tenantTableReportsService.excelListTableReportsDetailsForZxxljkzh(p_map);
			break;
		default:
			lists = tenantTableReportsService.excelListTableReportsByMap(p_map);
			break;
		}
		return lists;
	}

	/*
	 * 根据用户uuid，tableUuid及taskUUid获取测评信息
	 */
	@RequestMapping(value = "/getTableFactorJson", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getTableFactorJson(@RequestParam("userUuid") String userUuid,
			@RequestParam("tableUuid") String tableUuid, @RequestParam("taskUuid") String taskUuid) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_uuid", userUuid);
		String[] args = taskUuid.split(",");
		List<String> task_uuids = new ArrayList<>();
		for (int i = 0; i < args.length; i++) {
			task_uuids.add(args[i]);
		}
		map.put("table_uuid", tableUuid);
		map.put("task_uuids", task_uuids);
		TenantTableTaskInfo taskInfo = tenantTableTaskInfoService.selectTaskInfoByMap(map);
		if (taskInfo != null) {
			TenantTableReportsAttached tenantTableReport = tenantTableReportsAttachedService
					.findTableReportByUuid(taskInfo.getUuid());
			if (tenantTableReport != null && tenantTableReport.getFactorJson() != null)
				map.clear();
			map.put("factorJson", tenantTableReport.getFactorJson());
			map.put("answer", taskInfo.getAnswer());
			map.put("taskInfoUuid", taskInfo.getUuid());
			return map;
		}
		return null;
	}

	/**
	 * 添加新用户默认测评任务
	 * 
	 * @param userUuid    用户uuid
	 * @param frameworkId frameworkid
	 * @return
	 */
	@RequestMapping(value = "/addUserToDefaultTask", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData addUserToDefaultTask(@RequestParam("userUuid") String userUuid,
			@RequestParam("frameworkId") Long frameworkId) {
		ResponseData mResponseData = new ResponseData();
		TenantTableTasks tenantTableTasks = tenantTableTasksService.getDefaultTaskByFrameworkId(frameworkId);
		if (tenantTableTasks != null)
			mResponseData = addTaskUsersFortaskUuid(tenantTableTasks.getUuid(), null, userUuid, null, null);
		return mResponseData;
	}
	/*
	 * 取消测评报告
	 */

	@RequestMapping("/cancelTestTask")
	@ResponseBody

	public ResponseData cancelTestTask(@RequestParam("taskUuid") String taskUuid) {
		ResponseData mResponseData = null;
		try {
			mResponseData = new ResponseData();
			Map<String, Object> map1 = new HashMap<>();
			map1.put("task_uuid", taskUuid);
			List<Map<String, Object>> finishedcount = tenantTableReportsService.countFinishedisZero(taskUuid);
			Long counts = (Long) finishedcount.get(0).get("counts");
			BigDecimal finished = (BigDecimal) finishedcount.get(0).get("finished");
			// 1.判断测试进度 如果 finished==counts 测试进度100% 不允许取消
			if (finished.equals(new BigDecimal(counts))) {
				mResponseData.setCode(-1);
				mResponseData.setMsg("取消失败，测评任务已完成！");
				return mResponseData;
			} else {
				// 3. 测试进度<100 可以修改状态 进行取消操作
				TenantTableTasks tableTask = tenantTableTasksService.selectByPrimaryKey(taskUuid);
				tableTask.setStatus(TasksMethodEnum.tasks_cancel.getKey()); // 状态为10时取消
				tenantTableTasksService.updateByPrimaryKeySelective(tableTask);
			}
		} catch (Exception e) {
			logger.error("异常", e);
			mResponseData.setCode(-1);
			mResponseData.setMsg("取消失败");
		}
		return mResponseData;
	}

	@RequestMapping(value = "/getUserDigitalTableMsg", method = RequestMethod.POST)
	public ResponseData getUserDigitalTableMsg(@RequestParam("userUuid") String userUuid,
			@RequestParam("tableCodes") String tableCodes) {
		ResponseData mResponseData = new ResponseData();
		Map<String, Object> pmap = new HashMap<>();
		pmap.put("user_uuid", userUuid);
		pmap.put("table_codes", Arrays.asList(tableCodes.split(",")));
		List<Map<String, Object>> tableMsgs = tenantTableTasksService.getUserDigitalTableMsg(pmap);
		log.info("--------getUserDigitalTableMsg, 111=" + JSON.toJSONString(tableMsgs));
		pmap.clear();
		if (tableMsgs.size() > 0) {
			pmap.put("tableMsgs", JSON.toJSONString(tableMsgs));
			mResponseData.setData(pmap);
			log.info("--------getUserDigitalTableMsg, pmap=" + pmap.toString());
		}
		return mResponseData;
	}

	@RequestMapping(value = "/getTaskInfoAnswerAndFactor")
	public ResponseData getTaskInfoAnswerAndFactor(@RequestParam String taskInfoUuid) {
		TenantTableTaskInfo taskInfo = tenantTableTaskInfoService.selectByPrimaryKey(taskInfoUuid);
		TenantTableReportsAttached reportsAttached = tenantTableReportsAttachedService
				.findTableReportByUuid(taskInfoUuid);
		Map<String, Object> data = new HashMap<>();
		if (taskInfo != null && reportsAttached != null && taskInfo.getFinished() == 1) {
			SysTableBrief tableBrief = sysTableBriefService.selectByPrimaryKey(taskInfo.getTable_uuid());
			data.put("tableUuid", taskInfo.getTable_uuid());
			data.put("tableCode", tableBrief.getEnglish_name());
			data.put("answer", taskInfo.getAnswer());
			data.put("factorJson", reportsAttached.getFactorJson());
			data.put("userUuid", taskInfo.getUser_uuid());
		}
		ResponseData responseData = new ResponseData();
		responseData.setData(data);
		return responseData;
	}

	@RequestMapping(value = "/resetTableTaskInfo")
	private ResponseData resetTableTaskInfo(@RequestParam String taskInfoUuid) {
		ResponseData responseData = new ResponseData();

		String[] prefix = { "delete from tenant_table_reports where task_info_uuid='" + taskInfoUuid + "'",
				"delete from tenant_table_reports_attached where task_info_uuid='" + taskInfoUuid + "'",
				"delete from tenant_table_factors where task_info_uuid='" + taskInfoUuid + "'",
				"update tenant_table_task_info set finished=0,answer=NULL,answer_seconds=NULL,answer_time=NULL,submit_date=NULL where uuid='"
						+ taskInfoUuid + "'" };

		String[] resetPrefix = new String[prefix.length];
		System.arraycopy(prefix, 0, resetPrefix, 0, prefix.length);
		Connection conn = null;
		String result = "1";
		PreparedStatement pst = null;
		try {
			conn = sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
			// 设置事务为非自动提交
			conn.setAutoCommit(false);
//            Statement st = conn.createStatement();
			// 比起st，pst会更好些
			pst = conn.prepareStatement(" ");
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < resetPrefix.length; i++) {
				// 添加执行sql
				pst.addBatch(resetPrefix[i]);
				stringBuilder.append(resetPrefix[i] + ";\n");
			}
			logger.info("sql: " + stringBuilder);
			// 执行操作
			pst.executeBatch();
			// 提交事务
			conn.commit();
			logger.info("========= resetTable commit =========");
		} catch (SQLException e) {
			result = "-1";
			logger.error("SQLException:", e);
			logger.error("合并账号失败！");
		} finally {
			if (pst != null) {
				try {
					pst.close();
				} catch (SQLException throwables) {
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException throwables) {
				}
			}
		}
		return responseData;
	}

}